When using Python, we all have the moment of trying to figure out how to “manipulate” the date and time.
This is a cheat sheet I created that covers the most commonly used DateTime related functions in Python. If you want something simple but practical with examples, take a look!
We’ll cover all 7 popular topics below:
- Today’s date and time in different formats
- String to date conversion
- The Difference in DateTime calculation
- Datetime plus/minus a specific time
- Datetime comparison
- Time zones settings
- Unix timestamp / Epoch time calculation
Today’s date and time in different formats
Let’s warm-up from the most basic. Below is the code that prints the current year, month, date, hour, minute, seconds, and milliseconds.
In: from datetime import datetime
d = datetime.now() #today's datetime
d
Out:datetime.datetime(2019, 12, 22, 13, 14, 18, 193898)This is handy information, but often we only need part of it. We can print the different parts below.
In: print(d.weekday()) #day of week - Monday is 0 and Sunday is 6
print(d.year)
print(d.month)
print(d.day)
print(d.hour)
print(d.minute)
print(d.second)
Out: 6
2019
12
22
13
14
18Moreover, specific formats of the date/time might be needed. We can use the below list to customize different date formats. This can also be considered a way of converting date to string. The full list can be found here.

In: print(d.strftime("%A %d/%m/%Y")) # date to string
Out: Sunday 22/12/2019String to date conversion
Below are examples showing two popular strings being converted to date format:
In: date_string = '2016-02-01 12:00PM'
print(datetime.strptime(date_string, '%Y-%m-%d %I:%M%p'))
Out: 2016-02-01 12:00:00
In: date_string = '02/01/2016'
d2 = datetime.strptime(date_string, '%m/%d/%Y')
print(d2)
Out: 2016-02-01 00:00:00The Difference in DateTime calculation
The example below prints the difference in days (for example, today and February 1st, 2016):
In: from datetime import timedelta
d = datetime.now()
date_string = '2/01/2016'
d2 = datetime.strptime(date_string, '%m/%d/%Y')
print(d - d2)
Out: 1420 days, 13:18:27.386763We can also only print the difference between two date-times in days, weeks, or years, etc.
In: date_diff = (d - d2)/timedelta(days=1)
print('date_diff = {} days'.format(date_diff))
Out: date_diff = 1420.5544836430902 days
In: date_diff = (d - d2)/timedelta(weeks=1)
print('date_diff = {} weeks'.format(date_diff))
Out: date_diff = 202.93635480615575 weeks
In: date_diff = (d - d2)/timedelta(days=365)
print('date_diff = {} years'.format(date_diff))
Out: date_diff = 3.8919300921728497 yearsDatetime plus/minus a specific time
Let’s do some “time travel” by different time intervals of seconds, minutes, hours, days, weeks, or years:
In: print(d + timedelta(seconds=1)) # today + one second
print(d + timedelta(minutes=1)) # today + one minute
print(d + timedelta(hours=1)) # today + one hour
print(d + timedelta(days=1)) # today + one day
print(d + timedelta(weeks=1)) # today + one week
print(d + timedelta(days=1)*365) # today + one year
Out: 2019-12-22 13:18:28.386763
2019-12-22 13:19:27.386763
2019-12-22 14:18:27.386763
2019-12-23 13:18:27.386763
2019-12-29 13:18:27.386763
2020-12-21 13:18:27.386763Datetime comparison
The comparisons between dates are straightforward with usual comparison symbols:
In: print(d < (d2 +(timedelta(days=365*6)))) # d is no more than 6 years (assume each year has 365 days) after d2?
print(d > (d2 +(timedelta(weeks=52*6)))) # d is more than 6 years (assume each year has 52 weeks) after d2?
print(d != d2) # d2 is not the same date as d?
print(d == d2) # d2 is the same date as d?
Out: True
False
True
FalseTime zones settings
And we can also compare time in different time zones, such as Toronto and Shanghai:
In: import pytz
timezone = pytz.timezone("America/Toronto")
dtz = timezone.localize(d)
print(dtz.tzinfo)
print(dtz)
Out: America/Toronto
2019-12-22 13:18:27.386763-05:00
In: shanghai_dt = dtz.astimezone(pytz.timezone("Asia/Shanghai"))
print(shanghai_dt)
Out: 2019-12-23 02:18:27.386763+08:00
In: (dtz - shanghai_dt)/timedelta(days=1) # same datetimes
Out: 0.0If you are interested in the whole list of different time zones. Using the below code can print them:
In: for tz in pytz.all_timezones:
print(tz)
Out: Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
(Only showing the first three as examples)Unix timestamp / Epoch time calculation
Unix timestamps are commonly used for files in operating systems. Often they show up in datasets as well.
First, we can get the current Unix timestamp:
In: from datetime import timezone
dt_now = datetime.now(timezone.utc)
print(dt_now)
print(dt_now.tzinfo)
print(dt_now.timestamp()) # the unix timestamp.
Out: 2019-12-22 18:21:28.681380+00:00
UTC
1577038888.68138Also, we can convert Unix timestamp to DateTime format:
In: utc_timestamp = 1377050861.206272
unix_ts_dt = datetime.fromtimestamp(utc_timestamp, timezone.utc)
print(unix_ts_dt)
print(unix_ts_dt.astimezone(pytz.timezone("America/Toronto")))
print(unix_ts_dt.astimezone(pytz.timezone("Asia/Shanghai")))
Out: 2013-08-21 02:07:41.206272+00:00
2013-08-20 22:07:41.206272-04:00
2013-08-21 10:07:41.206272+08:00