Date Manipulation Functions¶
As part of our application, we often need to deal with dates. Let us get an overview about dealing with dates in Python.* datetime
is the main library to deal with dates.
datetime.datetime
anddatetime.date
are the classes as part ofdatetime
library that can be used to deal with dates.datetime.datetime
is primarily used for date with timestamp anddatetime.date
can be used for date with out timestamp.- When we try to print the date it will print as below (for datetime). It is due to the implementation of string representation functions such as
__str__
or__repr__
.datetime.datetime(2020, 10, 7, 21, 9, 1, 39414)
- We need to format the date using format string to display the date the way we want. These are typically used along with functions such as
strptime
andstrftime
.%Y
– 4 digit year%m
– 2 digit month%d
– 2 digit day with in month- There are quite a few other format strings, but these are the most important ones to begin with.
- Also,
datetime
library provides functions such asstrptime
to convert strings to date objects. - Other important modules to manipulate dates.
calendar
– to get the calendar related information for dates such as day name, month name etc.datetime.timedelta
– to perform date arithmetic
In [1]:
# Importing datetime
import datetime as dt
In [2]:
# Getting Current date with timestamp
dt.datetime.now()
Out[2]:
datetime.datetime(2022, 3, 16, 12, 26, 2, 344075)
In [3]:
# Getting Current date without timestamp
from datetime import date
date.today()
Out[3]:
datetime.date(2022, 3, 16)
In [4]:
# Converting date to a string in the form of yyyy-MM-dd (2020-10-07)
date.today().strftime('%Y-%m-%d')
Out[4]:
'2022-03-16'
In [5]:
# Converting date to a string in the form of dd-MM-yyyy (07-10-2020)
date.today().strftime('%d-%m-%Y')
Out[5]:
'16-03-2022'
In [6]:
# Converting date to a string in the form of yyyy/MM/dd (2020/10/07)
date.today().strftime('%Y/%m/%d')
Out[6]:
'2022/03/16'
In [7]:
# Converting date to an integer in the form of yyyyMMdd (20201007)
int(date.today().strftime('%Y%m%d'))
Out[7]:
20220316
In [8]:
# Converting time to a string in the form of yyyy-MM-dd HH:mm:SS (2020-10-08 19:25:31)
dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
Out[8]:
'2022-03-16 12:26:07'
In [9]:
# Converting date to a string in the form yyyyMMdd (20201007)
# We can represent this date as integer and hence we can convert the data type
int(date.today().strftime('%Y%m%d'))
Out[9]:
20220316
In [10]:
# Converting string which contains date using format yyyy-MM-dd as date
dt.datetime.strptime('2020-10-07', '%Y-%m-%d')
Out[10]:
datetime.datetime(2020, 10, 7, 0, 0)
In [11]:
dt.datetime.strptime('2020-10-07', '%Y-%m-%d').date()
Out[11]:
datetime.date(2020, 10, 7)
In [12]:
# Converting number which contains date using format yyyyMMdd as date
# strptime expects first argument to be string which contain date
# so we need to convert datatype of number to string
dt.datetime.strptime(20201007, '%Y%m%d')
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [12], in <cell line: 4>() 1 # Converting number which contains date using format yyyyMMdd as date 2 # strptime expects first argument to be string which contain date 3 # so we need to convert datatype of number to string ----> 4 dt.datetime.strptime(20201007, '%Y%m%d') TypeError: strptime() argument 1 must be str, not int
In [13]:
# Converting number which contains date using format yyyyMMdd as date
# strptime expects first argument to be string which contain date
# so we need to convert datatype of number to string
dt.datetime.strptime(str(20201007), '%Y%m%d')
Out[13]:
datetime.datetime(2020, 10, 7, 0, 0)
In [14]:
# Converting string which contains timestamp using format yyyy-MM-dd HH:mm:ss as date
dt.datetime.strptime('2020-10-07 21:09:10', '%Y-%m-%d %H:%M:%S')
Out[14]:
datetime.datetime(2020, 10, 7, 21, 9, 10)
In [15]:
import calendar, datetime as dt
In [16]:
d = dt.date.today()
In [17]:
d
Out[17]:
datetime.date(2022, 3, 16)
calendar
contains an attribute calledday_name
. It is a list like object.
In [18]:
type(calendar.day_name)
Out[18]:
calendar._localized_day
In [19]:
list(calendar.day_name)
Out[19]:
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
In [20]:
calendar.weekday?
Signature: calendar.weekday(year, month, day) Docstring: Return weekday (0-6 ~ Mon-Sun) for year, month (1-12), day (1-31). File: /usr/local/lib/python3.8/calendar.py Type: function
In [21]:
type(d)
Out[21]:
datetime.date
year
will return 4 digit year.
In [22]:
d.year
Out[22]:
2022
month
will return 1 or 2 digit month. It will be in the range of 1 to 12.
In [23]:
d.month
Out[23]:
3
day
will return 1 or 2 digit day. The range will be based up on the range of dates in a given month.
In [24]:
d.day
Out[24]:
16
calendar.weekday
takes year, month and day as argument and returns a number between 0 and 6. It typically starts with Monday.
In [25]:
calendar.weekday(d.year, d.month, d.day)
Out[25]:
2
- As
day_name
is list like object, we can pass the generated day number in[]
to get the day name.
In [26]:
calendar.day_name[calendar.weekday(d.year, d.month, d.day)]
Out[26]:
'Wednesday'