Cheat Sheet on dates

Cheat sheet on dates.

In [1]:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Out[1]:
run previous cell, wait for 2 seconds

string to datetime and datetime to string

see how to convert a string date into datetime format in python

In [2]:
import datetime
d = datetime.datetime.strptime("11/08/75", "%d/%m/%y")
d
Out[2]:
datetime.datetime(1975, 8, 11, 0, 0)
In [3]:
d.strftime("%Y-%m-%d")
Out[3]:
'1975-08-11'

now, time difference

In [4]:
from datetime import datetime
now = datetime.now()
now
Out[4]:
datetime.datetime(2017, 11, 9, 11, 30, 20, 895311)
In [5]:
delta = now - datetime(now.year - 1, 12, 31)
delta
Out[5]:
datetime.timedelta(313, 41452, 134562)
In [6]:
delta.days
Out[6]:
313

day of the year

In [7]:
now = datetime.now()
now
Out[7]:
datetime.datetime(2017, 11, 9, 11, 31, 7, 946012)
In [8]:
day_of_year = now.timetuple().tm_yday
day_of_year
Out[8]:
313
In [9]: