Everything about date & time in python

Posted on 02 Apr, 2021

Earth rotates just like my head trying to understand dates and time-zones.

Get current date & time

>>> import datetime
# without timezone
>>> datetime.datetime.now().strftime("%d %b, %Y (%I:%M:%S %p)")
'02 Apr, 2021 (01:37:43 PM)'

# with local timezone
>>> datetime.datetime.now(datetime.timezone.utc).astimezone().strftime("%d %b, %Y (%I:%M:%S %p) %Z")
'02 Apr, 2021 (01:38:20 PM) IST'

Current date/time to Unix timestamp

>>> import time
>>> t = datetime.datetime.now(datetime.timezone.utc).astimezone()
>>> t.timetuple()
time.struct_time(tm_year=2021, tm_mon=4, tm_mday=2, tm_hour=13, tm_min=43, tm_sec=15, tm_wday=4, tm_yday=92, tm_isdst=-1)
>>> time.mktime(t.timetuple())
1617351195.0

Unix timestamp to date/time

>>> import time
>>> t = datetime.datetime.now(datetime.timezone.utc).astimezone()
>>> unix_t = time.mktime(t.timetuple())
1617351195.0
>>> t = time.localtime(unix_t)
time.struct_time(tm_year=2021, tm_mon=4, tm_mday=2, tm_hour=13, tm_min=46, tm_sec=32, tm_wday=4, tm_yday=92, tm_isdst=0)
# verify
>>> time.strftime("%d %b, %Y (%I:%M:%S %p)", t)
'02 Apr, 2021 (01:46:32 PM IST)'

datetime object to string

>>> from datetime import datetime
>>> d = datetime.now()
>>> d
datetime.datetime(2020, 11, 7, 20, 15, 58, 389341)
>>> d.strftime("%d %b, %Y")
'07 Nov, 2020'

From string to datetime object

>>> from datetime import datetime
>>> date_string = "2020-06-20T08:22:54Z"
>>> datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2020, 6, 20, 8, 22, 54)

Both strptime & strftime can ofc be chained.

>>> from datetime import datetime
>>> date_string = "2020-06-20T08:22:54Z"
>>> datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%SZ').strftime("%d %b, %Y")

This can be handy when you are getting date/time fields from external resource (like an API) and only want to display a part of it (like days, month etc).

Format codes for strptime and strftime

Last updated