Python Datetime Module

In this notebook, we are going to discuss the datetime module, it's functionality, uses and it's pros and cons.

Datetime Module definition

The datetime module provides classes for manipulating dates and times. There can be numerous applications that require processing dates and times. The datetime module is very useful for dealing with different types of dates and times format.

The date and time objects can be either categorized as aware or naive depending on whether or not they include timezone information.

An aware object can identify itself relative to other time objects with the help of other parameters such as timezone and daylight saving information.

A naive object on the other hand doesn't contain enough information to identify itself to other date/time objects.

Datetime objects have an optional timezone information attribute tzinfo which we will cover later. The tzinfo lets us handle offset from UTC time, timezone name and whether daylight saving time is in effect.

Datetime available Data Types

Let us import the datetime module and try few examples to illustrate how it works.

In [ ]:
import datetime

datetime.time

By default, datetime.time assumes standard time conditions that is every day has 24*60*60 seconds. The attributes availabe for this class are:

  • hour
  • minute
  • second
  • microsecond
  • tzinfo

datetime.date

Similarly datetime.date by default assumes Georgian calendar. The attributes for this class are:

  • year
  • month
  • day

datetime.datetime

A combination of date and time. The attributes for this class are:

  • year
  • month
  • day
  • hour
  • minute
  • second
  • microsecond
  • tzinfo

datetime.timedelta

This is one of the most commonly used classes of the datetime module. The timedelta class enables us to calculate the difference between date, time and datetime object.

datetime.tzinfo

It is an abstract base class for timezone information. It is used to provide more control over timezones.

datetime.timezone

This is a class that implements the tzinfo abstract base class as a fixed offset from the UTC. It is mainly used for tzinfo because it maps the timezone to the UTC difference.

Examples of Python datetime

Get current date and time with different timezones

In [ ]:
datetime_object = datetime.datetime.now()
print(datetime_object)
print("Year: ", datetime_object.year)
print("Month: ", datetime_object.month)
print("Dat: ", datetime_object.day)
print("Hour: ", datetime_object.hour)
print("Minute: ", datetime_object.minute)
print("Second: ", datetime_object.second)
print("TimeZone info: ", datetime_object.tzinfo)
2021-08-21 03:18:46.014948
Year:  2021
Month:  8
Dat:  21
Hour:  3
Minute:  18
Second:  46
TimeZone info:  None

In the previous example note that the timezone info is none, this is due to the fact that we didn't make our datetime object time zone aware. Let us fix this by applying some changes...

In [ ]:
datetime_object = datetime.datetime.now()
# we will use the timezone class mentioned above in the
# available data types of the datetime module

datetime_object = datetime_object.replace(tzinfo=datetime.timezone.utc)
print(datetime_object)
print("Year: ", datetime_object.year)
print("Month: ", datetime_object.month)
print("Dat: ", datetime_object.day)
print("Hour: ", datetime_object.hour)
print("Minute: ", datetime_object.minute)
print("Second: ", datetime_object.second)
print("TimeZone info: ", datetime_object.tzinfo)
2021-08-21 03:18:46.829710+00:00
Year:  2021
Month:  8
Dat:  21
Hour:  3
Minute:  18
Second:  46
TimeZone info:  UTC

Now you can see that the affiliated timezone with the datetime object we created is set to UTC. We can also convert this datetime object to a more readable format using the isoformat method.

In [ ]:
print(datetime_object.isoformat())
2021-08-21T03:18:46.829710+00:00

Python pytz

In case we want to use a different timezone than UTC, we can use the pytz module as shown below.

In [ ]:
import pytz
# print(pytz.all_timezones_set)

new_timezone = pytz.timezone('Europe/Madrid')
datetime_object = datetime.datetime.now(tz=new_timezone)
# print(datetime_object)
print("Year: ", datetime_object.year)
print("Month: ", datetime_object.month)
print("Dat: ", datetime_object.day)
print("Hour: ", datetime_object.hour)
print("Minute: ", datetime_object.minute)
print("Second: ", datetime_object.second)
print("TimeZone info: ", datetime_object.tzinfo)
print(datetime_object.isoformat())
Year:  2021
Month:  8
Dat:  21
Hour:  5
Minute:  18
Second:  50
TimeZone info:  Europe/Madrid
2021-08-21T05:18:50.231715+02:00

Getting current date only

In [ ]:
day = datetime.date.today()
print(day)
2021-08-21

Creating a date object for specific date

If you want to create your own datetime object with a specific date, we can do that as well...

In [ ]:
day = datetime.date(2020, 8, 23)
print(day)
2020-08-23

Getting a date from a timestamp

A Unix timestamp is a number of seconds in UTC format between a particular date and January 1, 1970 at UTC. It's a very standard way of dealing with datetime objects.

The current timestamp at the moment of writing this notebook is: 1629516295 so let us explore how to extract information from this timestamp using datetime module.

In [ ]:
timestamp = 1629516295
datetime_object = datetime.datetime.fromtimestamp(timestamp)
# We also know that Unix timestamps are in UTC so we might as well 
# add the timezone info to our object.
datetime_object = datetime_object.replace(tzinfo=datetime.timezone.utc)
print(datetime_object)
print("Year: ", datetime_object.year)
print("Month: ", datetime_object.month)
print("Dat: ", datetime_object.day)
print("Hour: ", datetime_object.hour)
print("Minute: ", datetime_object.minute)
print("Second: ", datetime_object.second)
print("TimeZone info: ", datetime_object.tzinfo)
2021-08-21 03:24:55+00:00
Year:  2021
Month:  8
Dat:  21
Hour:  3
Minute:  24
Second:  55
TimeZone info:  UTC

Generating a timestamp from a datetime object

In [ ]:
datetime_object = datetime.datetime.now()
print("Timestamp: ", datetime_object.timestamp())
Timestamp:  1629516634.09742

Python timedelta

As explained earlier, timedelta can be used to represent difference between two dates or times which might come in handy in a lot of situations. Let us explore the following example.

Count the number of days between 24-07-2020 and 26-03-2021.

In [ ]:
start_date = datetime.date(2020, 7, 24)
end_date = datetime.date(2021, 3, 26)

# We can simply just subtract these two objects and the result would be
# a timedelta object

timedelta = end_date - start_date
print(type(timedelta))
print("Day difference: ", timedelta.days)
<class 'datetime.timedelta'>
Day difference:  245

Let's explore another example...

What will be the date if we add 28 days to todays date.

In [ ]:
today = datetime.date.today()

timedelta_needed = datetime.timedelta(days=28)

result_date = today + timedelta_needed

print(result_date)
2021-09-18

Python strftime()

The datetime module contains a very powerful method called strftime which helps us format the dates in whichever format we need.

In [ ]:
# current date and time
now = datetime.datetime.now(tz=pytz.timezone('UTC'))

t = now.strftime("%H:%M:%S")
print("time:", t)

s1 = now.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
print("mm/dd/YY:", s1)

s2 = now.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("dd/mm/YY:", s2)

# Timezone
print("Timezone: ", now.strftime("%Z"))

# Weekday
print("Weekday: ", now.strftime("%A"))

# Abbreviated weekday
print("Abbreviated Weekday: ", now.strftime("%a"))


# Locale's appropriate date and time representation
print("Locale representation: ", now.strftime("%c"))
time: 03:47:40
mm/dd/YY: 08/21/2021, 03:47:40
dd/mm/YY: 21/08/2021, 03:47:40
Timezone:  UTC
Weekday:  Saturday
Abbreviated Weekday:  Sat
Locale representation:  Sat Aug 21 03:47:40 2021

This is a link to a cheatsheet containing all available formats we can utilize to view our dates and/or times...

https://www.nbshare.io/notebook/510557327/Strftime-and-Strptime-In-Python/

Python strptime()

As opposed to the strftime method, the strptime method takes in a string and converts it into datetime object. This method takes two paramaters. These are:

  • Date string
  • Date Format

The second parameter (format) is referring to the format directives. The same ones we used in strftime ('%A, %d, %Z .. etc.). It acts in the way that tells Strptime what is the format of the datetime string to be processed. Now let us work on few examples.

In [3]:
import datetime
datetime_string = '08/23/21 15:23:52'

datetime_object = datetime.datetime.strptime(datetime_string, '%m/%d/%y %H:%M:%S')
print(type(datetime_object))
print(datetime_object)
<class 'datetime.datetime'>
2021-08-23 15:23:52

As you can see in the example above, the returned type is a datetime object and therefore we can manipulate it however we want using all the datetime modules classes and methods available. Let us work on few more examples to consolidate our understanding for this method.

In [4]:
datetime_string = '08/23/21 15:23:52'

date_object = datetime.datetime.strptime(datetime_string, '%m/%d/%y %H:%M:%S').date()

print(type(date_object))
print(date_object)

time_object = datetime.datetime.strptime(datetime_string, '%m/%d/%y %H:%M:%S').time()
print(type(time_object))
print(time_object)

# Notice below how the time representation has changed from the above example
# and that we now have a double colons. Observe how will we adjust the format
# of the strptime method so as to correctly parse the input string.
time_example = '15::23::26'
time_example_object = datetime.datetime.strptime(time_example, '%H::%M::%S')
print(type(time_example_object))
print(time_example_object)
<class 'datetime.date'>
2021-08-23
<class 'datetime.time'>
15:23:52
<class 'datetime.datetime'>
1900-01-01 15:23:26