Dates and Times in Python

Canonical import statements

import datetime as dt
import time as tm

The following returns the time in seconds since “the Epoch,” January 1, 1970, as a float.

tm.time()
1564433094.291373

The float can be converted to a datetime object.

dtnow = dt.datetime.fromtimestamp(tm.time())
dtnow
datetime.datetime(2019, 7, 29, 13, 44, 54, 302079)

There are several available accessor attributes for datetime objects

dtnow.year, dtnow.month, dtnow.day, dtnow.hour, dtnow.minute, dtnow.second
(2019, 7, 29, 13, 44, 54)

timedelta objects are time durations.

delta = dt.timedelta(days = 100)
delta
datetime.timedelta(days=100)

The today method of dt.date returns the current date as a date, not a datetime.

today = dt.date.today()
today
datetime.date(2019, 7, 29)

Perform math with date and timedelta objects using standard arithmetic operators.

today - delta
datetime.date(2019, 4, 20)