Skip to content

Datetime

Datetime representation

Code

import datetime

Create

Action Code Details
From ymdhms
datetime(year, month, day, hour, minute, second)
Current datetime
datetime.now()
Current datetime in UTC timezone
datetime.utcnow()
Unix epoch
datetime.fromtimestamp(0)
From date and time
datetime.combine(date, time)
Datetime from any valid ISO 8601 datetime string
datetime.fromisoformat(datetime_str)
e.g. 2023-01-30 23:59, 2023-01-30T23:59:01
Datetime from YYYY-MM-DD HH:mm:ss
x.strptime('%y-%m-%d %H:%M:%S')
Datetime from string (unknown format)
pandas.to_datetime('2023 Jan 5')
uses the pandas package
From total seconds since Unix epoch
datetime.fromtimestamp(n)
From total seconds since reference datetime
ref_datetime + timedelta(seconds=n)
From total days since Unix epoch
datetime.fromtimestamp(0) + timedelta(n)
From total days since reference datetime
ref_datetime + timedelta(n)

Constants

Action Code Details
Earliest representable datetime
datetime.min
Latest representable datetime
datetime.max

Test

Action Code Details
Is datetime
isinstance(x, datetime.datetime)
Same moment
x == y
Up to x.resolution precision (usually 1Ξs)
Happens before y
x < y
Happens after y
x > y

Extract

Action Code Details
Year
x.year
Month
x.month
Day
x.day
Hour
x.hour
Minute
x.minute
Second
x.second
Microsecond
x.microsecond
Weekday number
x.isoweekday()
Mon=1, Sun=7
Weekday number (zero-based)
x.weekday()
Mon=0, Sun=6

Derive

Action Code Details
Change to first day of year
x.replace(month=1, day=1)
Change to first day of month
x.replace(day=1)
Change year to y
x.replace(year=y)
In UTC timezone
?
Shift forward by n days
x + timedelta(days=n)
Shift forward by n seconds
x + timedelta(seconds=n)

Convert

Action Code Details
Date component
x.date()
Time component
x.time()
Timestamp (seconds from Unix epoch), as float
x.timestamp()
Format datetime as ISO 8601
x.isoformat()
e.g., 2023-01-01T23:59:00
Format readable datetime of consistent length
x.ctime()
e.g., Sun Jan 1 23:59:00 2023
Format datetime as YYYY-MM-DD
x.date().isoformat()
e.g., 2024-01-31
Format datetime as DD-MMM-YYYY
x.strftime('%d-%b-%Y')
e.g., 31-Jan-2023
Format datetime as HH:mm
x.strftime('%H:%M')
e.g., 23:59
Format datetime as HH:mm:ss
x.strftime('%H:%M:%S')
e.g., 23:59:00
Format datetime as YYYY-MM-DD HH:mm:ss
x.strftime('%y-%m-%d %H:%M:%S')
Named tuple
x.timetuple()