Python Datetime and 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 new date object

All three arguments (year, day and month) are required.

from datetime import date

# december 25th, 2018
d = date(2018,30,12)
# datetime.date(2018, 12, 25)
Twitter Linkedin YC Hacker News Reddit

Build new 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)
# datetime.datetime(2016, 5, 10, 12, 30)

Build new datetime object from string

In other words, parse a string into a datetime object.

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)

datetime_obj
# datetime.datetime(2016, 12, 1, 12, 34, 56)
Twitter Linkedin YC Hacker News Reddit

Build new 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)
# datetime.datetime(2016, 5, 10, 12, 30, tzinfo=datetime.timezone(datetime.timedelta(0, 10800)))

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'
Twitter Linkedin YC Hacker News Reddit

Add seconds to a datetime object

Use a timedelta.

from datetime import datetime,timedelta

date_before = datetime.now()

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

date_after = date_before + timedelta(seconds=5)

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 timedelta object.

from datetime import datetime,timedelta

date_before = datetime.now()

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

delta = date_after - date_before

print(delta.seconds)
# 5

Today's date

from datetime import date

d = date.today()
d
#datetime.date(2018, 11, 11)

Current datetime (now)

from datetime import datetime

dt = datetime.now()
dt
# datetime.datetime(2018, 11, 11, 17, 56, 2, 701694)

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))
current_millis
# 1541966251776

References

Dialogue & Discussion