站內搜尋:Yahoo搜尋的結果,如果沒有給完整的網址,請在站內再搜尋一次!

2019-08-06

Python : 日期時間的計算運算

  1. 匯入日期時間模組,以指定的方式,建立日期時間物件
  2. # 匯入 datetime 模組,並以 mDT 作為 datetime 的別名
    import datetime as mDT
    # 使用 mDT 模組,建立一個現在的日期時間(datetime)物件 oNow
    oNow=mDT.datetime.now()
    # 指定 年 月 日 時 分 秒,建立日期時間物件
    oTheDateTime=mDT.datetime(year=2019,month=8,day=8,hour=17,minute=30,second=0)
    print(oTheDateTime.strftime('%Y-%m-%d %H:%M:%S'))
    # >>>2019-08-08 17:30:00
    oTheDateTime2=mDT.datetime(2018,1,23,8,15,20)
    print(oTheDateTime2.strftime('%Y-%m-%d %H:%M:%S'))
    # >>>2018-01-23 08:15:20
  3. 透過 timedelta(...) 進行日期時間的加減計算
    oAddOneDay=mDT.timedelta(days=+1)
    oTheDateTime=oTheDateTime+oAddOneDa
    print(oTheDateTime.strftime('%Y-%m-%d %H:%M:%S'))
    # >>>2019-08-09 17:30:00
    oAdd21Days=mDT.timedelta(weeks=2,days=6,hours=23,minutes=50,seconds=600)
    # 以上合計剛好 21天
    oTheDateTime2=oTheDateTime2-oAdd21Days+oAddOneDay
    print(oTheDateTime2.strftime('%Y-%m-%d %H:%M:%S'))
    # >>>2018-01-03 08:15:20
    # 23日 - 21天 + 1天 = 3日
  4. timedelta 可以用時間單位:週、天、時、分、秒,當計算的單位,但不可以用 年、月。
    # oAfter2Months=mDT.timedelta(months=2)
    # >>>TypeError: 'months' is an invalid keyword argument for __new__()
    # oAfter2Years=mDT.timedelta(years=2)
    # >>>TypeError: 'years' is an invalid keyword argument for __new__()
  5. 參考資料:
    https://docs.python.org/3.7/library/datetime.html?highlight=datetime%20format#datetime.date.__format__

沒有留言:

張貼留言