Python時間變數筆記 | How to manipulate time variables in python

Example: x days later

import datetime as dt
today = dt.datetime.today()
one_month_later = today + dt.timedelta(days=30)
print(f"today: {today}")
print(f"one_month_later: {one_month_later}")
2020-07-13 20:52:21.473270
one_month_later: 2020-08-12 20:52:21.473270

Example: datetime to string

today = dt.datetime.today()
print(today.strftime('%Y%m%d')
print(today.strftime('%Y-%m-%d')
20210125
2021-01-25

Example: input date/time from string: strptime (string parsed to time)

%y (lower case) year in 2 digits, like 20
%Y (capital case) year in 4 digits, like 2020

>>> dt.datetime.strptime('2020-01-01', '%Y-%m-%d')
datetime.datetime(2020, 1, 1, 0, 0)

>>> dt.datetime.strptime('20-01-01', '%y-%m-%d')
datetime.datetime(2020, 1, 1, 0, 0)

Example: number of days between two dates

兩個datetime.datetime type變數相減得到datetime.timedelta

>>> today - one_month_later
datetime.timedelta(days=-30)

>>> print(today - one_month_later)
-30 days, 0:00:00

>>> d = today - one_month_later
>>> d.days
-30

Leave a Comment

Your email address will not be published.