To understand how Pandas works with time series, we need to understand the datetime
module of Python. The main object types of this module are below
date
- stores year, month, day using Gregorian calendartime
- stores hours, minutes, seconds, microsecondsdatetime
- both date and timetimedelta
- difference between two datetime values - represented as days, seconds, microseconds
In [1]:
from datetime import datetime
In [2]:
now = datetime.now()
now
Out[2]:
In [5]:
(now.year, now.month, now.day, now.hour, now.minute)
Out[5]:
You can get the time difference between two dates as timedelta
objects
In [6]:
delta = datetime(2020,3,12) - datetime(2020,9,25)
delta
Out[6]:
In [8]:
(delta.days, delta.seconds)
Out[8]:
In [9]:
from datetime import timedelta
In [12]:
datetime.now() + timedelta(days=25)
Out[12]:
In [13]:
datetime.now() - timedelta(days=20, hours=5)
Out[13]:
In [16]:
stamp = datetime.now()
str(stamp)
Out[16]:
In [24]:
stamp.strftime('%Y-%m-%d-%H-%M-%S')
Out[24]:
The table below gives most popular format strings to use with strftime
.
%Y
- 4 digit year%y
- 2 digit year%m
- 2 digit month [02,10]%d
- 2 digit day [01,22]%H
- hours in 24 hour clock, 2 digits%I
- hours in 12 hour clock, 2 digits%M
- minutes, 2 digits%S
- seconds, 2 digits%w
- weekday as integer [0 (sun) - 6 (sat)]%U
- week number, 2 digits, from 00-53. First Sunday of the year is the start of the week (1) and days before belong to week 0%W
- week number where Monday is the start of the week%z
- UTC time zone offset as +HHMM or -HHMM, empty is time zone is unknown (naive)%F
- shortcut for %Y-%m-%d
(2020-03-12)%D
- shortcut for %m/%d/%y
(03/12/20)If you notice, year, month, date are lower while hour, min, sec are upper cases.
In [28]:
datetime.now().strftime('Current hour is %I and week number is %U')
Out[28]:
In [29]:
datetime.now().strftime('%z')
Out[29]:
In [30]:
datetime.now().strftime('%D')
Out[30]:
In [33]:
stamp_str = '03/12/20'
datetime.strptime(stamp_str, '%m/%d/%y')
Out[33]:
In [34]:
from dateutil.parser import parse
In [35]:
parse('03/12/20')
Out[35]:
In [ ]: