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
The float can be converted to a
dtnow = dt.datetime.fromtimestamp(tm.time()) dtnow
datetime.datetime(2019, 7, 29, 13, 44, 54, 302079)
There are several available accessor attributes for
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
The today method of dt.date returns the current date as a
date, not a
today = dt.date.today() today
datetime.date(2019, 7, 29)
Perform math with
timedelta objects using standard arithmetic operators.
today - delta
datetime.date(2019, 4, 20)
Some of this content was taken from my notes on the Coursera course, "Introduction to Data Science in Python".