Python 3 Date and Time Manipulation: Examples

Last updated:
Table of Contents

WIP Alert This is a work in progress. Current information is correct but more content may be added in the future.

Build a datetime object

E.g.: May 10, 2016 at 12:30:00

from datetime import datetime

# year, month, day, hours, minutes, seconds ...
obj = datetime(2016,5,10,12,30,0,0)

Build a datetime object with timezone information

E.g.: May 10, 2016 at 12:30:00, on UTC-03:00

from datetime import datetime,timezone,timedelta

# UTC+03:00
tz = timezone(timedelta(hours=3))

obj = datetime(2016,5,10,12,30,0,0, tzinfo=tz)

Build a date object

from datetime import date

t = date.today()

Today's date

from datetime import date

t = date.today()

Format a date according to ISO 8601

from datetime import date

d = date(2002, 12, 4)

print(d.isoformat())
# '2002-12-04'

Format a date according to a custom format

from datetime import date

d = date(2002, 12, 4)

print(d.strftime("%A, %b %d %Y"))
# Wednesday, Dec 04 2002

For days of the month without zero-padding, use %-d:

from datetime import date

d = date(2002, 12, 4)

print(d.strftime("%A, %b %-d %Y"))
# Wednesday, Dec 4 2002

References

Dialogue & Discussion