This notebook was prepared by Donne Martin. Source and license info is on GitHub.
from datetime import datetime, date, time
year = 2015
month = 1
day = 20
hour = 7
minute = 28
second = 15
dt = datetime(year, month, day, hour, minute, second)
dt.hour, dt.minute, dt.second
Extract the equivalent date object:
dt.date()
Extract the equivalent time object:
dt.time()
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:
dt.replace(minute=0, second=0)
Format a datetime string:
dt.strftime('%m/%d/%Y %H:%M')
Convert a string into a datetime object:
datetime.strptime('20150120', '%Y%m%d')
Get the current datetime:
dt_now = datetime.now()
Subtract two datetime fields to create a timedelta:
delta = dt_now - dt
delta
Add a datetime and a timedelta to get a new datetime:
dt + delta