Dates and Times

  • Basics
  • strftime
  • strptime
  • timedelta

Basics

In [4]:
from datetime import datetime, date, time
In [5]:
year = 2017
month = 8
day = 29
hour =18
minute = 4
second = 15
In [6]:
dt = datetime(year, month, day, hour, minute, second)
In [7]:
dt.hour, dt.minute, dt.second
Out[7]:
(18, 4, 15)

Extract the equivalent date object:

In [8]:
dt.date()
Out[8]:
datetime.date(2017, 8, 29)

Extract the equivalent time object:

In [9]:
dt.time()
Out[9]:
datetime.time(18, 4, 15)

When aggregating or grouping time series data, it is sometimes useful to replace fields of a series of datetimes such as zeroing out the minute and second fields:

In [10]:
dt.replace(minute=0, second=0)
Out[10]:
datetime.datetime(2017, 8, 29, 18, 0)

strftime

Format a datetime string:

In [11]:
dt.strftime('%m/%d/%Y %H:%M')
Out[11]:
'08/29/2017 18:04'

strptime

Convert a string into a datetime object:

In [13]:
datetime.strptime('20170829', '%Y%m%d')
Out[13]:
datetime.datetime(2017, 8, 29, 0, 0)

timedelta

Get the current datetime:

In [14]:
dt_now = datetime.now()

Subtract two datetime fields to create a timedelta:

In [15]:
delta = dt_now - dt
delta
Out[15]:
datetime.timedelta(0, 8, 836993)

Add a datetime and a timedelta to get a new datetime:

In [16]:
dt + delta
Out[16]:
datetime.datetime(2017, 8, 29, 18, 4, 23, 836993)
In [ ]: