Python Datetime Module Tutorial

Python Datetime Module Tutorial

Working with various dates and times in computer applications is a universal requirement. When writing programs in Python, software developers can lean on the Python Datetime Module for help in calculating these sometimes complex concepts. The Datetime module in Python is extensive and offers functions for efficient time formatting and manipulation, as well as date and time math calculations. In this Python Datetime Module Tutorial, we’ll take a look at some of the commonly used functions in the datetime module and how to make use of them.


datetime.date()

You can instantiate date objects from the date class. A date object represents a date (year, month and day).

This example shows a simple date creation in Python.

import datetime

date = datetime.date(2023, 7, 4)

print(date)
2023-07-04

datetime.date.today()

today(…) method of builtins.type instance
Current date or datetime: same as self.__class__.fromtimestamp(time.time()).

To get the current date or datetime, you can reach into the .today() function as seen in this code snippet.

import datetime

date = datetime.date.today()

print(date)
2022-01-18
import datetime

# Once you have a datetime stored in a variable, it is easy to get access to the year, month, and day as shown here.
date = datetime.date.today()

print(date.year)
print(date.month)
print(date.day)
2022
1
18
import datetime

date = datetime.date.today()

print(date.weekday())    # 0-6 (0 is Monday) Monday to Sunday
print(date.isoweekday()) # 1-7 (1 is Monday) Monday to Sunday
1
2

datetime.timedelta()

class timedelta(builtins.object)
   Difference between two datetime values.
   
   timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
   
   All arguments are optional and default to 0.
   Arguments may be integers or floats, and may be positive or negative.
   
   Methods defined here:
   
   __abs__(self, /)
       abs(self)
   
   __add__(self, value, /)
       Return self+value.
   
   __bool__(self, /)
       self != 0
   
   __divmod__(self, value, /)
       Return divmod(self, value).
   
   __eq__(self, value, /)
       Return self==value.
   
   __floordiv__(self, value, /)
       Return self//value.
   
   __ge__(self, value, /)
       Return self>=value.
   
   __getattribute__(self, name, /)
       Return getattr(self, name).
   
   __gt__(self, value, /)
       Return self>value.
   
   __hash__(self, /)
       Return hash(self).
   
   __le__(self, value, /)
       Return self<=value.
   
   __lt__(self, value, /)
       Return self (cls, state)
   
   __repr__(self, /)
       Return repr(self).
   
   __rfloordiv__(self, value, /)
       Return value//self.
   
   __rmod__(self, value, /)
       Return value%self.
   
   __rmul__(self, value, /)
       Return value*self.
   
   __rsub__(self, value, /)
       Return value-self.
   
   __rtruediv__(self, value, /)
       Return value/self.
   
   __str__(self, /)
       Return str(self).
   
   __sub__(self, value, /)
       Return self-value.
   
   __truediv__(self, value, /)
       Return self/value.
   
   total_seconds(...)
       Total seconds in the duration.
   
   ----------------------------------------------------------------------
   Static methods defined here:
   
   __new__(*args, **kwargs) from builtins.type
       Create and return a new object.  See help(type) for accurate signature.
   
   ----------------------------------------------------------------------
   Data descriptors defined here:
   
   days
       Number of days.
   
   microseconds
       Number of microseconds (>= 0 and less than 1 second).
   
   seconds
       Number of seconds (>= 0 and less than 1 day).
   
   ----------------------------------------------------------------------
   Data and other attributes defined here:
   
   max = datetime.timedelta(days=999999999, seconds=86399, microseconds=9...
   
   min = datetime.timedelta(days=-999999999)
   
   resolution = datetime.timedelta(microseconds=1)

Timedeltas are an important part of working with dates and times in Python. Timedeltas allow you to look add and subtract a given amount of time from the current time or any arbitrary time value.

import datetime

current = datetime.date.today()

future = datetime.timedelta(days=7)

print(current + future)
2022-01-25
import datetime

current = datetime.date.today()

tdelta = datetime.timedelta(days=7)

print(f'Today is {current}')
print(f'One week from now is {current + tdelta}')
print(f'One week ago was {current - tdelta}')
Today is 2022-01-18
One week from now is 2022-01-25
One week ago was 2022-01-11
import datetime

date1 = datetime.date.today()
date2 = datetime.date(2020, 1, 1)

sub_dates = date1 - date2
add_dates = date2 - date1

print(f'Subtracting dates: {sub_dates}')
print(f'Adding dates: {add_dates}')

# Adding or subracting dates results in a timedelta object
print(f'type(sub_dates): {type(sub_dates)}')
print(f'type(add_dates): {type(add_dates)}')
Subtracting dates: 748 days, 0:00:00
Adding dates: -748 days, 0:00:00
type(sub_dates): <class 'datetime.timedelta'>
type(add_dates): <class 'datetime.timedelta'>

datetime.time()

class time(builtins.object)
   time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object
   
   All arguments are optional. tzinfo may be None, or an instance of
   a tzinfo subclass. The remaining arguments may be ints.
   
   Methods defined here:
   
   __eq__(self, value, /)
       Return self==value.
   
   __format__(...)
       Formats self with strftime.
   
   __ge__(self, value, /)
       Return self>=value.
   
   __getattribute__(self, name, /)
       Return getattr(self, name).
   
   __gt__(self, value, /)
       Return self>value.
   
   __hash__(self, /)
       Return hash(self).
   
   __le__(self, value, /)
       Return self<=value.
   
   __lt__(self, value, /)
       Return self (cls, state)
   
   __reduce_ex__(...)
       __reduce_ex__(proto) -> (cls, state)
   
   __repr__(self, /)
       Return repr(self).
   
   __str__(self, /)
       Return str(self).
   
   dst(...)
       Return self.tzinfo.dst(self).
   
   isoformat(...)
       Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].
       
       The optional argument timespec specifies the number of additional terms
       of the time to include. Valid options are 'auto', 'hours', 'minutes',
       'seconds', 'milliseconds' and 'microseconds'.
   
   replace(...)
       Return time with new specified fields.
   
   strftime(...)
       format -> strftime() style string.
   
   tzname(...)
       Return self.tzinfo.tzname(self).
   
   utcoffset(...)
       Return self.tzinfo.utcoffset(self).
   
   ----------------------------------------------------------------------
   Class methods defined here:
   
   fromisoformat(...) from builtins.type
       string -> time from time.isoformat() output
   
   ----------------------------------------------------------------------
   Static methods defined here:
   
   __new__(*args, **kwargs) from builtins.type
       Create and return a new object.  See help(type) for accurate signature.
   
   ----------------------------------------------------------------------
   Data descriptors defined here:
   
   fold
   
   hour
   
   microsecond
   
   minute
   
   second
   
   tzinfo
   
   ----------------------------------------------------------------------
   Data and other attributes defined here:
   
   max = datetime.time(23, 59, 59, 999999)
   
   min = datetime.time(0, 0)
   
   resolution = datetime.timedelta(microseconds=1)

To work with just the time and omit the date portion of a datetime, you can make use of datetime.time directly. Here are a few examples of how to do that showing how to get access to the hour, minute, second, and microsecond of a time object.

import datetime

t = datetime.time(5, 25, 1, 1234)

print(t)
print(t.hour)
print(t.minute)
print(t.second)
print(t.microsecond)
05:25:01.001234
5
25
1
1234

datetime.datetime()

class datetime(date)
   datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
   
   The year, month and day arguments are required. tzinfo may be None, or an
   instance of a tzinfo subclass. The remaining arguments may be ints.
   
   Method resolution order:
       datetime
       date
       builtins.object
   
   Methods defined here:
   
   __add__(self, value, /)
       Return self+value.
   
   __eq__(self, value, /)
       Return self==value.
   
   __ge__(self, value, /)
       Return self>=value.
   
   __getattribute__(self, name, /)
       Return getattr(self, name).
   
   __gt__(self, value, /)
       Return self>value.
   
   __hash__(self, /)
       Return hash(self).
   
   __le__(self, value, /)
       Return self<=value.
   
   __lt__(self, value, /)
       Return self (cls, state)
   
   __reduce_ex__(...)
       __reduce_ex__(proto) -> (cls, state)
   
   __repr__(self, /)
       Return repr(self).
   
   __rsub__(self, value, /)
       Return value-self.
   
   __str__(self, /)
       Return str(self).
   
   __sub__(self, value, /)
       Return self-value.
   
   astimezone(...)
       tz -> convert to local time in new timezone tz
   
   ctime(...)
       Return ctime() style string.
   
   date(...)
       Return date object with same year, month and day.
   
   dst(...)
       Return self.tzinfo.dst(self).
   
   isoformat(...)
       [sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].
       sep is used to separate the year from the time, and defaults to 'T'.
       The optional argument timespec specifies the number of additional terms
       of the time to include. Valid options are 'auto', 'hours', 'minutes',
       'seconds', 'milliseconds' and 'microseconds'.
   
   replace(...)
       Return datetime with new specified fields.
   
   time(...)
       Return time object with same time but with tzinfo=None.
   
   timestamp(...)
       Return POSIX timestamp as float.
   
   timetuple(...)
       Return time tuple, compatible with time.localtime().
   
   timetz(...)
       Return time object with same time and tzinfo.
   
   tzname(...)
       Return self.tzinfo.tzname(self).
   
   utcoffset(...)
       Return self.tzinfo.utcoffset(self).
   
   utctimetuple(...)
       Return UTC time tuple, compatible with time.localtime().
   
   ----------------------------------------------------------------------
   Class methods defined here:
   
   combine(...) from builtins.type
       date, time -> datetime with same date and time fields
   
   fromisoformat(...) from builtins.type
       string -> datetime from datetime.isoformat() output
   
   fromtimestamp(...) from builtins.type
       timestamp[, tz] -> tz's local time from POSIX timestamp.
   
   now(tz=None) from builtins.type
       Returns new datetime object representing current time local to tz.
       
         tz
           Timezone object.
       
       If no tz is specified, uses local timezone.
   
   strptime(...) from builtins.type
       string, format -> new datetime parsed from a string (like time.strptime()).
   
   utcfromtimestamp(...) from builtins.type
       Construct a naive UTC datetime from a POSIX timestamp.
   
   utcnow(...) from builtins.type
       Return a new datetime representing UTC day and time.
   
   ----------------------------------------------------------------------
   Static methods defined here:
   
   __new__(*args, **kwargs) from builtins.type
       Create and return a new object.  See help(type) for accurate signature.
   
   ----------------------------------------------------------------------
   Data descriptors defined here:
   
   fold
   
   hour
   
   microsecond
   
   minute
   
   second
   
   tzinfo
   
   ----------------------------------------------------------------------
   Data and other attributes defined here:
   
   max = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
   
   min = datetime.datetime(1, 1, 1, 0, 0)
   
   resolution = datetime.timedelta(microseconds=1)
   
   ----------------------------------------------------------------------
   Methods inherited from date:
   
   __format__(...)
       Formats self with strftime.
   
   isocalendar(...)
       Return a named tuple containing ISO year, week number, and weekday.
   
   isoweekday(...)
       Return the day of the week represented by the date.
       Monday == 1 ... Sunday == 7
   
   strftime(...)
       format -> strftime() style string.
   
   toordinal(...)
       Return proleptic Gregorian ordinal.  January 1 of year 1 is day 1.
   
   weekday(...)
       Return the day of the week represented by the date.
       Monday == 0 ... Sunday == 6
   
   ----------------------------------------------------------------------
   Class methods inherited from date:
   
   fromisocalendar(...) from builtins.type
       int, int, int -> Construct a date from the ISO year, week number and weekday.
       
       This is the inverse of the date.isocalendar() function
   
   fromordinal(...) from builtins.type
       int -> date corresponding to a proleptic Gregorian ordinal.
   
   today(...) from builtins.type
       Current date or datetime:  same as self.__class__.fromtimestamp(time.time()).
   
   ----------------------------------------------------------------------
   Data descriptors inherited from date:
   
   day
   
   month
   
   year

Many times it makes sense to simply use datetime.datetime rather than datetime.time. The reason being is you might want to have access to both the date and time during program development. We can see this in action in these datetime code examples. With this approach, one object gets you access to the date, time, year, month, day, hour, minute, second and microsecond. Very handy!

import datetime

dt = datetime.datetime(2019, 5, 25, 12, 30, 45, 123456)

print(dt)
2019-05-25 12:30:45.123456
import datetime

dt = datetime.datetime(2019, 5, 25, 12, 30, 45, 123456)

print(f'The date is {dt.date()}')
print(f'The time is {dt.time()}')
print(f'The year is {dt.year}')
print(f'The month is {dt.month}')
print(f'The day is {dt.day}')
print(f'The hour is {dt.hour}')
print(f'The minute is {dt.minute}')
print(f'The second is {dt.second}')
print(f'The microsecond is {dt.microsecond}')
The date is 2019-05-25
The time is 12:30:45.123456
The year is 2019
The month is 5
The day is 25
The hour is 12
The minute is 30
The second is 45
The microsecond is 123456
import datetime

dt_today = datetime.datetime.today()
dt_now = datetime.datetime.now()
dt_utcnow = datetime.datetime.utcnow()

print(dt_today)
print(dt_now)
print(dt_utcnow)
2022-01-18 11:30:22.684051
2022-01-18 11:30:22.684051
2022-01-18 16:30:22.684051

Timezones with pytz


pytz.UTC

class UTC(pytz.tzinfo.BaseTzInfo)
   UTC
   
   Optimized UTC implementation. It unpickles using the single module global
   instance defined beneath this class declaration.
   
   Method resolution order:
       UTC
       pytz.tzinfo.BaseTzInfo
       datetime.tzinfo
       builtins.object
   
   Methods defined here:
   
   __reduce__(self)
   
   __repr__(self)
   
   __str__(self)
   
   dst(self, dt)
   
   fromutc(self, dt)
   
   localize(self, dt, is_dst=False)
       Convert naive time to local time
   
   normalize(self, dt, is_dst=False)
       Correct the timezone information on the given datetime
   
   tzname(self, dt)
   
   utcoffset(self, dt)
   
   ----------------------------------------------------------------------
   Data and other attributes defined here:
   
   zone = 'UTC'
   
   ----------------------------------------------------------------------
   Data descriptors inherited from pytz.tzinfo.BaseTzInfo:
   
   __dict__
       dictionary for instance variables (if defined)
   
   __weakref__
       list of weak references to the object (if defined)
   
   ----------------------------------------------------------------------
   Methods inherited from datetime.tzinfo:
   
   __getattribute__(self, name, /)
       Return getattr(self, name).
   
   ----------------------------------------------------------------------
   Static methods inherited from datetime.tzinfo:
   
   __new__(*args, **kwargs) from builtins.type
       Create and return a new object.  See help(type) for accurate signature.

Timezone support can be handled with the pytz module or the datetime.timezone() function. The pytz is a bit more full-featured and is recommended by the official Python docs so let’s look at a few examples of how to use pytz with the datetime module.

import datetime
import pytz

dt = datetime.datetime(2022, 6, 17, 12, 30, 45, tzinfo=pytz.UTC)

print(dt)
2022-06-17 12:30:45+00:00
import datetime
import pytz

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

dt_today = datetime.datetime.today(tz=pytz.UTC)  # fails: TypeError: datetime.today() takes no keyword arguments
dt_utcnow = datetime.datetime.utcnow(tz=pytz.UTC)  # fails: TypeError: datetime.utcnow() takes no keyword arguments
2022-01-18 16:39:59.276067+00:00
import datetime
import pytz

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

dt_east = dt_utcnow.astimezone(pytz.timezone('US/Eastern'))
dt_central = dt_utcnow.astimezone(pytz.timezone('US/Central'))
dt_west = dt_utcnow.astimezone(pytz.timezone('US/Pacific'))

print(dt_east)
print(dt_central)
print(dt_west)
2022-01-18 11:43:44.010293-05:00
2022-01-18 10:43:44.010293-06:00
2022-01-18 08:43:44.010293-08:00
import datetime
import pytz

for tz in pytz.all_timezones:
    print(tz)
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
Africa/Kinshasa
Africa/Lagos
Africa/Libreville
Africa/Lome
Africa/Luanda
Africa/Lubumbashi
Africa/Lusaka
Africa/Malabo
Africa/Maputo
Africa/Maseru
Africa/Mbabane
Africa/Mogadishu
Africa/Monrovia
Africa/Nairobi
Africa/Ndjamena
Africa/Niamey
Africa/Nouakchott
Africa/Ouagadougou
Africa/Porto-Novo
Africa/Sao_Tome
Africa/Timbuktu
Africa/Tripoli
Africa/Tunis
Africa/Windhoek
America/Adak
America/Anchorage
America/Anguilla
America/Antigua
America/Araguaina
America/Argentina/Buenos_Aires
America/Argentina/Catamarca
America/Argentina/ComodRivadavia
America/Argentina/Cordoba
America/Argentina/Jujuy
America/Argentina/La_Rioja
America/Argentina/Mendoza
America/Argentina/Rio_Gallegos
America/Argentina/Salta
America/Argentina/San_Juan
America/Argentina/San_Luis
America/Argentina/Tucuman
America/Argentina/Ushuaia
America/Aruba
America/Asuncion
America/Atikokan
America/Atka
America/Bahia
America/Bahia_Banderas
America/Barbados
America/Belem
America/Belize
America/Blanc-Sablon
America/Boa_Vista
America/Bogota
America/Boise
America/Buenos_Aires
America/Cambridge_Bay
America/Campo_Grande
America/Cancun
America/Caracas
America/Catamarca
America/Cayenne
America/Cayman
America/Chicago
America/Chihuahua
America/Coral_Harbour
America/Cordoba
America/Costa_Rica
America/Creston
America/Cuiaba
America/Curacao
America/Danmarkshavn
America/Dawson
America/Dawson_Creek
America/Denver
America/Detroit
America/Dominica
America/Edmonton
America/Eirunepe
America/El_Salvador
America/Ensenada
America/Fort_Nelson
America/Fort_Wayne
America/Fortaleza
America/Glace_Bay
America/Godthab
America/Goose_Bay
America/Grand_Turk
America/Grenada
America/Guadeloupe
America/Guatemala
America/Guayaquil
America/Guyana
America/Halifax
America/Havana
America/Hermosillo
America/Indiana/Indianapolis
America/Indiana/Knox
America/Indiana/Marengo
America/Indiana/Petersburg
America/Indiana/Tell_City
America/Indiana/Vevay
America/Indiana/Vincennes
America/Indiana/Winamac
America/Indianapolis
America/Inuvik
America/Iqaluit
America/Jamaica
America/Jujuy
America/Juneau
America/Kentucky/Louisville
America/Kentucky/Monticello
America/Knox_IN
America/Kralendijk
America/La_Paz
America/Lima
America/Los_Angeles
America/Louisville
America/Lower_Princes
America/Maceio
America/Managua
America/Manaus
America/Marigot
America/Martinique
America/Matamoros
America/Mazatlan
America/Mendoza
America/Menominee
America/Merida
America/Metlakatla
America/Mexico_City
America/Miquelon
America/Moncton
America/Monterrey
America/Montevideo
America/Montreal
America/Montserrat
America/Nassau
America/New_York
America/Nipigon
America/Nome
America/Noronha
America/North_Dakota/Beulah
America/North_Dakota/Center
America/North_Dakota/New_Salem
America/Nuuk
America/Ojinaga
America/Panama
America/Pangnirtung
America/Paramaribo
America/Phoenix
America/Port-au-Prince
America/Port_of_Spain
America/Porto_Acre
America/Porto_Velho
America/Puerto_Rico
America/Punta_Arenas
America/Rainy_River
America/Rankin_Inlet
America/Recife
America/Regina
America/Resolute
America/Rio_Branco
America/Rosario
America/Santa_Isabel
America/Santarem
America/Santiago
America/Santo_Domingo
America/Sao_Paulo
America/Scoresbysund
America/Shiprock
America/Sitka
America/St_Barthelemy
America/St_Johns
America/St_Kitts
America/St_Lucia
America/St_Thomas
America/St_Vincent
America/Swift_Current
America/Tegucigalpa
America/Thule
America/Thunder_Bay
America/Tijuana
America/Toronto
America/Tortola
America/Vancouver
America/Virgin
America/Whitehorse
America/Winnipeg
America/Yakutat
America/Yellowknife
Antarctica/Casey
Antarctica/Davis
Antarctica/DumontDUrville
Antarctica/Macquarie
Antarctica/Mawson
Antarctica/McMurdo
Antarctica/Palmer
Antarctica/Rothera
Antarctica/South_Pole
Antarctica/Syowa
Antarctica/Troll
Antarctica/Vostok
Arctic/Longyearbyen
Asia/Aden
Asia/Almaty
Asia/Amman
Asia/Anadyr
Asia/Aqtau
Asia/Aqtobe
Asia/Ashgabat
Asia/Ashkhabad
Asia/Atyrau
Asia/Baghdad
Asia/Bahrain
Asia/Baku
Asia/Bangkok
Asia/Barnaul
Asia/Beirut
Asia/Bishkek
Asia/Brunei
Asia/Calcutta
Asia/Chita
Asia/Choibalsan
Asia/Chongqing
Asia/Chungking
Asia/Colombo
Asia/Dacca
Asia/Damascus
Asia/Dhaka
Asia/Dili
Asia/Dubai
Asia/Dushanbe
Asia/Famagusta
Asia/Gaza
Asia/Harbin
Asia/Hebron
Asia/Ho_Chi_Minh
Asia/Hong_Kong
Asia/Hovd
Asia/Irkutsk
Asia/Istanbul
Asia/Jakarta
Asia/Jayapura
Asia/Jerusalem
Asia/Kabul
Asia/Kamchatka
Asia/Karachi
Asia/Kashgar
Asia/Kathmandu
Asia/Katmandu
Asia/Khandyga
Asia/Kolkata
Asia/Krasnoyarsk
Asia/Kuala_Lumpur
Asia/Kuching
Asia/Kuwait
Asia/Macao
Asia/Macau
Asia/Magadan
Asia/Makassar
Asia/Manila
Asia/Muscat
Asia/Nicosia
Asia/Novokuznetsk
Asia/Novosibirsk
Asia/Omsk
Asia/Oral
Asia/Phnom_Penh
Asia/Pontianak
Asia/Pyongyang
Asia/Qatar
Asia/Qostanay
Asia/Qyzylorda
Asia/Rangoon
Asia/Riyadh
Asia/Saigon
Asia/Sakhalin
Asia/Samarkand
Asia/Seoul
Asia/Shanghai
Asia/Singapore
Asia/Srednekolymsk
Asia/Taipei
Asia/Tashkent
Asia/Tbilisi
Asia/Tehran
Asia/Tel_Aviv
Asia/Thimbu
Asia/Thimphu
Asia/Tokyo
Asia/Tomsk
Asia/Ujung_Pandang
Asia/Ulaanbaatar
Asia/Ulan_Bator
Asia/Urumqi
Asia/Ust-Nera
Asia/Vientiane
Asia/Vladivostok
Asia/Yakutsk
Asia/Yangon
Asia/Yekaterinburg
Asia/Yerevan
Atlantic/Azores
Atlantic/Bermuda
Atlantic/Canary
Atlantic/Cape_Verde
Atlantic/Faeroe
Atlantic/Faroe
Atlantic/Jan_Mayen
Atlantic/Madeira
Atlantic/Reykjavik
Atlantic/South_Georgia
Atlantic/St_Helena
Atlantic/Stanley
Australia/ACT
Australia/Adelaide
Australia/Brisbane
Australia/Broken_Hill
Australia/Canberra
Australia/Currie
Australia/Darwin
Australia/Eucla
Australia/Hobart
Australia/LHI
Australia/Lindeman
Australia/Lord_Howe
Australia/Melbourne
Australia/NSW
Australia/North
Australia/Perth
Australia/Queensland
Australia/South
Australia/Sydney
Australia/Tasmania
Australia/Victoria
Australia/West
Australia/Yancowinna
Brazil/Acre
Brazil/DeNoronha
Brazil/East
Brazil/West
CET
CST6CDT
Canada/Atlantic
Canada/Central
Canada/Eastern
Canada/Mountain
Canada/Newfoundland
Canada/Pacific
Canada/Saskatchewan
Canada/Yukon
Chile/Continental
Chile/EasterIsland
Cuba
EET
EST
EST5EDT
Egypt
Eire
Etc/GMT
Etc/GMT+0
Etc/GMT+1
Etc/GMT+10
Etc/GMT+11
Etc/GMT+12
Etc/GMT+2
Etc/GMT+3
Etc/GMT+4
Etc/GMT+5
Etc/GMT+6
Etc/GMT+7
Etc/GMT+8
Etc/GMT+9
Etc/GMT-0
Etc/GMT-1
Etc/GMT-10
Etc/GMT-11
Etc/GMT-12
Etc/GMT-13
Etc/GMT-14
Etc/GMT-2
Etc/GMT-3
Etc/GMT-4
Etc/GMT-5
Etc/GMT-6
Etc/GMT-7
Etc/GMT-8
Etc/GMT-9
Etc/GMT0
Etc/Greenwich
Etc/UCT
Etc/UTC
Etc/Universal
Etc/Zulu
Europe/Amsterdam
Europe/Andorra
Europe/Astrakhan
Europe/Athens
Europe/Belfast
Europe/Belgrade
Europe/Berlin
Europe/Bratislava
Europe/Brussels
Europe/Bucharest
Europe/Budapest
Europe/Busingen
Europe/Chisinau
Europe/Copenhagen
Europe/Dublin
Europe/Gibraltar
Europe/Guernsey
Europe/Helsinki
Europe/Isle_of_Man
Europe/Istanbul
Europe/Jersey
Europe/Kaliningrad
Europe/Kiev
Europe/Kirov
Europe/Lisbon
Europe/Ljubljana
Europe/London
Europe/Luxembourg
Europe/Madrid
Europe/Malta
Europe/Mariehamn
Europe/Minsk
Europe/Monaco
Europe/Moscow
Europe/Nicosia
Europe/Oslo
Europe/Paris
Europe/Podgorica
Europe/Prague
Europe/Riga
Europe/Rome
Europe/Samara
Europe/San_Marino
Europe/Sarajevo
Europe/Saratov
Europe/Simferopol
Europe/Skopje
Europe/Sofia
Europe/Stockholm
Europe/Tallinn
Europe/Tirane
Europe/Tiraspol
Europe/Ulyanovsk
Europe/Uzhgorod
Europe/Vaduz
Europe/Vatican
Europe/Vienna
Europe/Vilnius
Europe/Volgograd
Europe/Warsaw
Europe/Zagreb
Europe/Zaporozhye
Europe/Zurich
GB
GB-Eire
GMT
GMT+0
GMT-0
GMT0
Greenwich
HST
Hongkong
Iceland
Indian/Antananarivo
Indian/Chagos
Indian/Christmas
Indian/Cocos
Indian/Comoro
Indian/Kerguelen
Indian/Mahe
Indian/Maldives
Indian/Mauritius
Indian/Mayotte
Indian/Reunion
Iran
Israel
Jamaica
Japan
Kwajalein
Libya
MET
MST
MST7MDT
Mexico/BajaNorte
Mexico/BajaSur
Mexico/General
NZ
NZ-CHAT
Navajo
PRC
PST8PDT
Pacific/Apia
Pacific/Auckland
Pacific/Bougainville
Pacific/Chatham
Pacific/Chuuk
Pacific/Easter
Pacific/Efate
Pacific/Enderbury
Pacific/Fakaofo
Pacific/Fiji
Pacific/Funafuti
Pacific/Galapagos
Pacific/Gambier
Pacific/Guadalcanal
Pacific/Guam
Pacific/Honolulu
Pacific/Johnston
Pacific/Kiritimati
Pacific/Kosrae
Pacific/Kwajalein
Pacific/Majuro
Pacific/Marquesas
Pacific/Midway
Pacific/Nauru
Pacific/Niue
Pacific/Norfolk
Pacific/Noumea
Pacific/Pago_Pago
Pacific/Palau
Pacific/Pitcairn
Pacific/Pohnpei
Pacific/Ponape
Pacific/Port_Moresby
Pacific/Rarotonga
Pacific/Saipan
Pacific/Samoa
Pacific/Tahiti
Pacific/Tarawa
Pacific/Tongatapu
Pacific/Truk
Pacific/Wake
Pacific/Wallis
Pacific/Yap
Poland
Portugal
ROC
ROK
Singapore
Turkey
UCT
US/Alaska
US/Aleutian
US/Arizona
US/Central
US/East-Indiana
US/Eastern
US/Hawaii
US/Indiana-Starke
US/Michigan
US/Mountain
US/Pacific
US/Samoa
UTC
Universal
W-SU
WET
Zulu

The strftime() method returns a string representing date and time using date, time or datetime object. This is a handy tool to create very human readable and friendly to look at string representations of date and time.

import datetime
import pytz

dt_east = datetime.datetime.now(pytz.timezone('US/Eastern'))

friendly_format = dt_east.strftime('%A, %B %d, %Y')

print(friendly_format)
Tuesday, January 18, 2022

The strftime() method is very flexible and by using a combination of the values below as arguments to the function, you can create almost any style of date time you can imagine.

Code Example Description
%a Sun Weekday as locale’s abbreviated name.
%A Sunday Weekday as locale’s full name.
%w 0 Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.
%d 08 Day of the month as a zero-padded decimal number.
%-d 8 Day of the month as a decimal number. (Platform specific)
%b Sep Month as locale’s abbreviated name.
%B September Month as locale’s full name.
%m 09 Month as a zero-padded decimal number.
%-m 9 Month as a decimal number. (Platform specific)
%y 13 Year without century as a zero-padded decimal number.
%Y 2013 Year with century as a decimal number.
%H 07 Hour (24-hour clock) as a zero-padded decimal number.
%-H 7 Hour (24-hour clock) as a decimal number. (Platform specific)
%I 07 Hour (12-hour clock) as a zero-padded decimal number.
%-I 7 Hour (12-hour clock) as a decimal number. (Platform specific)
%p AM Locale’s equivalent of either AM or PM.
%M 06 Minute as a zero-padded decimal number.
%-M 6 Minute as a decimal number. (Platform specific)
%S 05 Second as a zero-padded decimal number.
%-S 5 Second as a decimal number. (Platform specific)
%f 000000 Microsecond as a decimal number, zero-padded on the left.
%z +0000 UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive).
%Z UTC Time zone name (empty string if the object is naive).
%j 251 Day of the year as a zero-padded decimal number.
%-j 251 Day of the year as a decimal number. (Platform specific)
%U 36 Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0.
%W 35 Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0.
%c Sun Sep 8 07:06:05 2013 Locale’s appropriate date and time representation.
%x 09/08/13 Locale’s appropriate date representation.
%X 07:06:05 Locale’s appropriate time representation.
%% % A literal ‘%’ character.

It is also common to go From String to Datetime. To do this you can use the strptime() function as seen in this code example.

import datetime
import pytz

friendly_format = 'Tuesday, January 18, 2022'

dt = datetime.datetime.strptime(friendly_format, '%A, %B %d, %Y')

print(dt)
2022-01-18 00:00:00

Learn More About Python Datetime


Python Datetime Module Tutorial Summary

In this tutorial, you learned about programming with dates and times in Python and why it is important to understand how to use the datetime module. As you can see, the datetime module is vast and does require a fair amount of practice to get the hang of all the features.