Python Datetime Examples

Python Datetime Examples

Last updated:
Table of Contents

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

For examples on date arithmetic, see Python Date/Datetime Arithmetic Examples: Adding, Subtracting, etc

Build new Date object

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.

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

Example: "2019-10-20"

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

TEMPLATE: datetime(<year>, <month>, <day>, <hour>, <minute>, <seconds>)

from datetime import datetime

# May 10, 2016 at 12:30:00
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 December, 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)

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'

Date to Datetime at zero hours

Use datetime.datetime.combine(<date_obj>, datetime.time.min)

import datetime
from datetime import date

date_obj = date(2023, 1, 1)

datetime_obj = datetime.datetime.combine(date_obj, datetime.time.min)
# >>> 2023-01-01 00:00:00

Datetime to Date

Call .date() on the datetime object

from datetime import datetime

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

d = dt.date()
# >>> 2019-10-20

ISO 8601 string to Datetime

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

from datetime import date

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

today.day
# >>> 29

Get day of week deom date

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

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

Get start of week from date

Assuming the start of the week is Sunday.

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

from datetime import date, timedelta

# April 7 2020 is a Tuesday
dt = 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)

Get start of month from date

To get the first day of the month for a given date object, build another object passing day = 1:

from datetime import date

d = date(2023,12,15)

# using the same args from d, except the day
first_day_of_month = date(d.year, d.month, 1)

first_day_of_month
# >>> datetime.date(2023, 12, 1)

References