/ PYTHON

Python Datetime, Timedelta, and Pytz Tutorial

Python is a powerful programming language that is widely used in many industries today. In this tutorial, we will be exploring the datetime module in Python.

This module allows you to work with dates and times, which can be helpful for many tasks. We will be discussing some of the most important modules and functions within the datetime module so that you can start using them in your own programs. So let’s get started!

Please follow along with the video and the Python Datetime Jupyter Notebook.

Install Pytz

You don’t need to install datetime because it comes with the Python standard library. You do need to install Pytz, however. You can do this with the following command:

!pip install pytz

Import Datetime and Pytz

Even though datetime is part of the standard library, we still need to import it. And obviously, we’ll need to import pytz as well.

import datetime
import pytz

Create Dates, Times & Datetimes

Dates, times, and datetimes are moments in time. Dates are just the day component. Times are just the time component. And datetimes include both the day and time component.

date = datetime.date(2019,9,30)
print(date)

time = datetime.time(6,30,9, 123456)
print(time)

dt = datetime.datetime(2019,9,30,6,30,9,123456)
print(dt)

print(type(date))
print(type(time))
print(type(datetime))


2019-09-30
06:30:09.123456
2019-09-30 06:30:09.123456
<class 'datetime.date'>
<class 'datetime.time'>
<class 'module'>

today = datetime.date.today()
print(today)

now = datetime.datetime.now()
print(now)


2022-01-07
2022-01-07 11:12:52.071975

Create Datetimes from Strings

We can create parse strings to create datetimes using strptime.

datetime_string = "10 10 2021 13:37:00"
parsed_time = datetime.datetime.strptime(datetime_string, '%m %d %Y %X')
print(parsed_time)

datetime_string = "Thursday, December 20, 21 1:37 PM"
more_complex = datetime.datetime.strptime(datetime_string,
                                          '%A, %B %d, %y %I:%M %p')
print(type(more_complex))
print(more_complex)

2021-10-10 13:37:00
<class 'datetime.datetime'>
2021-12-20 13:37:00

Create Timedeltas

Timedeltas are durations in time. We can add and subtract timedeltas from dates and add and subtract timedeltas from other timedeltas.

from datetime import timedelta

daysdelta = datetime.timedelta(days=5)
future = now + daysdelta
print(future)

daysdelta = datetime.timedelta(days=-5)
past = now + daysdelta
print(past)

alldelta = timedelta(days=1,
                    seconds=1,
                    milliseconds=1,
                    minutes=1,
                    hours=1,
                    weeks=1)
print(alldelta)
future = now + alldelta
print(future)

2022-01-12 11:12:52.071975
2022-01-02 11:12:52.071975
8 days, 1:01:01.001000
2022-01-15 12:13:53.072975

daysdelta - alldelta

datetime.timedelta(days=-14, seconds=82738, microseconds=999000)

Accessing Datetime & Timedelta Attributes

Discovering and accessing datetime and timedelta attributes is easy.

print(dir(now)[-40:]) # shortend for display purposes
print(now.min)
print(dir(alldelta)[-7:])
print(alldelta.days)
['astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fold', 'fromisocalendar',
'fromisoformat', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat',
'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resolution',
'second', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'today', 'toordinal',
'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year']
0001-01-01 00:00:00
['days', 'max', 'microseconds', 'min', 'resolution', 'seconds', 'total_seconds']
8

Adding Timezones to Datetimes using Pytz

Adding timezones using pytz is also easy. We need to add a timezone when creating our datetime or replace the timezone on an existing datetime.

now.tzinfo == None

True

now = datetime.datetime.now(tz=pytz.UTC)
print(now)

dt_utc = datetime.datetime(2021,10,10,9,30,6,123456, tzinfo=pytz.UTC)
print(dt_utc)
dt_utc

2022-01-07 16:33:43.540085+00:00
2021-10-10 09:30:06.123456+00:00

datetime.datetime(2021, 10, 10, 9, 30, 6, 123456, tzinfo=<UTC>)

print(now)
now = datetime.datetime.now().replace(tzinfo=pytz.timezone('America/New_York'))
print(now)

2022-01-07 16:33:43.540085+00:00
2022-01-07 11:34:49.651145-04:56

Get a List of All Pytz Timezones

If you’re not sure what timezones are available using Pytz, you can use common_timezones and all_timezones to identify your options.

print(pytz.all_timezones)
    ['Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', 'Africa/Algiers', 'Africa/Asmara', 'Africa/Asmera',
    'Africa/Bamako', 'Africa/Bangui', 'Africa/Banjul', 'Africa/Bissau', 'Africa/Blantyre', 'Africa/Brazzaville',
    'Africa/Bujumbura', 'Africa/Cairo', 'Africa/Casablanca', 'Africa/Ceuta', 'Africa/Conakry', 'Africa/Dakar',
    'Africa/Dar_es_Salaam', 'Africa/Djibouti', 'Africa/Douala', 'Africa/El_Aaiun', 'Africa/Freetown', 'Africa/Gaborone'
    'Africa/Harare', 'Africa/Johannesburg', 'Africa/Juba', 'Africa/Kampala', 'Africa/Khartoum', 'Africa/Kigali', ... ]
leo

Leo Smigel

Based in Pittsburgh, Analyzing Alpha is a blog by Leo Smigel exploring what works in the markets.