Python datetime


Create datetime object

import datetime
# create from int
d = datetime.datetime(2005, 7, 14)
d = datetime.date(2005, 7, 14)
# create from str
d = datetime.datetime.strptime('20010101','%Y%m%d')

Datetime to string

s = d.strftime('%Y%m%d')

Datetime algebra

d2 = d + datetime.timedelta(1)

Calculate calendar day

DOY = d.timetuple().tm_yday

Generate a datetime series

import pandas as pd
year = 2020
datetime_series = pd.date_range(start='%s-01-01'%year, end='%s-12-31'%year, freq='D')

Back