Python Datetime Examples

Last updated:
Table of Contents

HEADS-UP The module is called datetime but there's also the datetime (and the date, time, etc ) class

Build 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 datetime object from string

from datetime import datetime

# 1st of January, 2016
date_str = "01-12-2016 12:34:56"

format = "%d-%m-%Y %H:%M:%S"

datetime_obj = datetime.strptime(date_str,format)

print(datetime_obj)
# datetime.datetime(2016, 12, 1, 12, 34, 56)

Build datetime object with timezone

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)

Format datetime object to string

from datetime import datetime

obj = datetime(2016,5,10,12,30,0,0)
print(obj.strftime('%d %b, %Y %H:%M:%S'))
# '10 May, 2016 12:30:00'

Add seconds to a datetime object

Just use a timedelta.

from datetime import datetime,timedelta

date_before = datetime.now()

print(date_before)
# 2018-03-08 22:34:56.769632

# 5 seconds time
delta = timedelta(0,5)

date_after = date_before + delta

print(date_after)
# 2018-03-08 22:35:01.769632

Get datetime difference in seconds

You can call .seconds (also hours, minutes, etc) on the delta object.

from datetime import datetime,timedelta

date_before = datetime.now()

# added 5 seconds
date_after = date_before + timedelta(0,5)

delta = date_after - date_before

print(delta.seconds)
# 5

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 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

Get current timestamp in milliseconds

import time

current_millis = int(round(time.time() * 1000))

References

Dialogue & Discussion