This is a cheat sheet I have created to covers the most commonly used datetime related functions in Python.
This is very useful information but often we only need part of it. We can print the different parts below.
We can also only print the difference of two datetimes in days, weeks or years, etc.
Let’s do some “time travel” by different time intervals of second, minute, hour, day, week or year:
The comparisons between dates are straightforward with usual comparison symbols:
And we can also compare time in different time zones, such as Toronto and India:
If you guys want something simple but practical with examples, take a look!
Let’s warm up from the most basic.
- Today’s date and time in different formats
- String to date conversion
- Difference in datetime calculation
- Datetime plus/minus a certain period of time
- Datetime comparison
- Time zones settings
Let’s warm up from the most basic.
Below is the code that will print the current year, month, date, hour, minute, seconds and milliseconds.
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)
For certain formats of the date/time 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 fom here
Below are examples showing two popular strings being converted to date format:
Difference in datetime calculation
The example below prints the difference in days (for example today and February 1st, 2016):
print(d.strftime("%A %d/%m/%Y")) # date to string
String to date conversionBelow are examples showing two popular strings being converted to date format:
date_string = '2020-02-01 12:00PM'
print(datetime.strptime(date_string, '%Y-%m-%d %I:%M%p'))
date_string = '02/01/2020'
d = datetime.strptime(date_string, '%m/%d/%Y')
print(d)
Difference in datetime calculation
The example below prints the difference in days (for example today and February 1st, 2016):
from datetime import timedelta
d1 = datetime.now()
date_string = '2/01/2016'
d2 = datetime.strptime(date_string, '%m/%d/%Y')
print(d1 - d2)
date_diff = (d - d2)/timedelta(days=1)
print('date_diff = {} days'.format(date_diff))
date_diff = (d - d2)/timedelta(weeks=1)
print('date_diff = {} weeks'.format(date_diff))
date_diff = (d - d2)/timedelta(days=365)
print('date_diff = {} years'.format(date_diff))
Datetime plus/minus a certain period of timeLet’s do some “time travel” by different time intervals of second, minute, hour, day, week or year:
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
Datetime comparisonThe comparisons between dates are straightforward with usual comparison symbols:
# d is no more than 6 years (assume each year has 365 days) after d2?
print(d < (d2 +(timedelta(days=365*6))))
# d is more than 6 years (assume each year has 52 weeks) after d2?
print(d > (d2 +(timedelta(weeks=52*6))))
print(d != d2) # d2 is not the same date as d?
print(d == d2) # d2 is the same date as d
Time zones settingsAnd we can also compare time in different time zones, such as Toronto and India:
import pytz
timezone = pytz.timezone("America/Toronto")
dtz = timezone.localize(d)
print(dtz.tzinfo)
print(dtz)
india_dt = dtz.astimezone(pytz.timezone("Asia/Calcutta"))
print(india_dt)
print((dtz - india_dt)/timedelta(days=1)) # same datetime
For the list of all timezone
for tz in pytz.all_timezones:
print(tz)
Thanks
Saurabh Sharma
Happy Coding !!!
Saurabh Sharma
Happy Coding !!!