Working with Dates and Times in Python
Max Shron
Data Scientist and Author
date()
class takes a year, month, and day as argumentsdate
object has accessors like .year
, and also methods like .weekday()
date
objects can be compared like numbers, using min()
, max()
, and sort()
date
from another to get a timedelta
date
objects into strings, use the .isoformat()
or .strftime()
methodsdatetime()
class takes all the arguments of date()
, plus an hour, minute, second, and microseconddatetime
with the .replace()
methodtimedelta
into an integer with its .total_seconds()
method.strptime()
and dates into strings with .strftime()
datetime
is "timezone aware" when it has its tzinfo
set. Otherwise it is "timezone naive"datetime
how to align itself to UTC, the universal time standard.replace()
method to change the timezone of a datetime
, leaving the date and time the same.astimezone()
method to shift the date and time to match the new timezonedateutil.tz
provides a comprehensive, updated timezone databaseparse_dates
argument to be the list of columns which should be parsed as datetimesparse_dates
doesn't work, use the pd.to_datetime()
function.groupby()
lets you calculate aggregates per group. For example, .first()
, .min()
or .mean()
.resample()
groups rows on the basis of a datetime
column, by year, month, day, and so on.tz_localize()
to set a timezone, keeping the date and time the same.tz_convert()
to change the date and time to match a new timezoneWorking with Dates and Times in Python