Back to Data Science Ipython Notebooks

Dates and Times

python-data/datetime.ipynb

latest1.3 KB
Original Source

This notebook was prepared by Donne Martin. Source and license info is on GitHub.

Dates and Times

  • Basics
  • strftime
  • strptime
  • timedelta

Basics

python
from datetime import datetime, date, time
python
year = 2015
month = 1
day = 20
hour = 7
minute = 28
second = 15
python
dt = datetime(year, month, day, hour, minute, second)
python
dt.hour, dt.minute, dt.second

Extract the equivalent date object:

python
dt.date()

Extract the equivalent time object:

python
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:

python
dt.replace(minute=0, second=0)

strftime

Format a datetime string:

python
dt.strftime('%m/%d/%Y %H:%M')

strptime

Convert a string into a datetime object:

python
datetime.strptime('20150120', '%Y%m%d')

timedelta

Get the current datetime:

python
dt_now = datetime.now()

Subtract two datetime fields to create a timedelta:

python
delta = dt_now - dt
delta

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

python
dt + delta