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

Unless otherwise noted Python version 3.6+ is used in all examples.

Build new Date object

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

Use date(year,month,day)

from datetime import date

# december 25th, 2018
d = date(2018, 12, 25)
# datetime.date(2018, 12, 25)

Get current date

Use date.today()

from datetime import date

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

Date to ISO 8601 string

Call .isoformat() on the date object.

from datetime import date

d = date(2002, 12, 4)

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

Date to string, custom format

Call .strftime(<format>) on the date object.

from datetime import date

d = date(2002, 12, 4)

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

Date to string, no zero-padding

Use %-d to disable zero-padding:

from datetime import date

d = date(2002, 12, 4)

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

String to Date

Convert an ISO 8601 date string ("YYYY-MM-DD") into a Date object.

Solution: Read it into a Datetime using strptime() then build a new Date object from that.

Example: read the string "2019-10-20" into a Date object

from datetime import date,datetime

# read the string into a datetime object
dt=datetime.strptime("2019-10-20","%Y-%m-%d")
# >>> datetime.datetime(2019, 10, 20, 0, 0)

# then build a date object
d = date(dt.year,dt.month,dt.day)
# >>> datetime.date(2019, 10, 20)

New Datetime object

Example: 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)

Current datetime

Use datetime.now()

from datetime import datetime

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

Datetime to ISO 8601 String

The ISO format for timestamps has a 'T' separating the date from the time part.

Use .isoformat():

from datetime import datetime

dt = datetime.now()

dt.isoformat()
# >>> '2020-02-25T01:19:18.900361'

String to Datetime

View all strptime formats here

Use datetime.strptime(date_string,format_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)

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

New Datetime 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)))

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

Datetime to Date

Use the default date constructor: date(year,month,day)

from datetime import date,datetime

dt = datetime.now()
# >>> 2019-10-20 15:53:19.085418

# get year, month and day form the datetime object
d = date(dt.year,dt.month,dt.day)
# >>> 2019-10-20

Add seconds to Datetime

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

Datetime difference in seconds

Adding and subtracting Datetime objects gives you a TimeDelta object as result.

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

ISO 8601 string to Datetime

If you're on Python 3.7+, use datetime.fromisoformat() instead

Use strptime with this format: "%Y-%m-%dT%H:%M:%S.%f"

Example: read "2019-10-20T15:54:53.840416" into a datetime object

from datetime import datetime

dt = datetime.now()
iso_datetime_string = dt.isoformat()
# >>> '2019-10-20T15:54:53.840416'

datetime.strptime(iso_datetime_string,"%Y-%m-%dT%H:%M:%S.%f")
# >>> datetime.datetime(2019, 10, 20, 15, 54, 53, 840416)

Current timestamp in milliseconds

import time

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

Get day of month from date object

from datetime import date

today = date.today()
# >>> datetime.date(2019, 4, 29)

today.day
# >>> 29

Get day of week from date object

Method Day numbers
isoweekday()Monday is 1, Sunday is 7
weekday()Monday is 0, Sunday is 6

Example date: 29 April, 2019 is a Monday.

from datetime import date

d = date.today()
# >>> datetime.date(2019, 4, 29)

# with weekday(), 0 means monday 
d.weekday()
# >>> 0

# with isoweekday(), 1 means monday
d.isoweekday()
# >>> 1

Truncate date to start of week

This assumes the start of the week is Sunday.

Subtract the date by: timedelta(days = (dt.weekday() + 1) % 7)

Example:


# April 7 2020 is a Tuesday
dt_today = date(2020,4,7)

# calculate the start of the week.
dt_start_of_week = dt - timedelta(days = (dt.weekday() + 1) % 7)

# April 5 2020 is the start of the Week (sunday)
dt_start_of_week
# >>> datetime.date(2020, 4, 5)

References

Dialogue & Discussion