Frank Joseph I'm an innovative software engineer and technical writer passionate about the developer community. I'm interested in building applications that run on the internet.

Python datetime module: Handling dates and time

7 min read 2175

Python Datetime Module

Python is a high-level, general-purpose, interpreted programming language built with simplicity and readability in mind. With various modules available that simplify the language, Python is beginner-friendly and easy to use; one example is the Python datetime module, which helps us manage the complexities of date and time computation in Python.

One major problem every developer encounters when working with dates and time is the issue of differences in time zones across the globe. With the Python datetime module, you can write programs that get the day of the month, the day of the week, and the local date and time in minutes, hours, seconds, or milliseconds.

The Python datetime module consists of five main classes, date, time, tzinfo, DateTime, and timedelta. In this article, we’ll discuss these classes, covering relevant examples for each.

Prerequisites

To follow along with this article, you’ll need the following:

  • A basic understanding of Python
  • The latest version of Python installed on your computer
  • An IDE, preferably PyCharm

Let’s get started!

datetime module classes

The Python datetime module helps us handle time-related events like years, months, weeks, days, hours, minutes, seconds, etc. Although the most commonly used classes are DateTime, Date, Time, Tzinfo, and Timedelta, to get other elements present in the Python datetime module, run the following code:

import datetime
print(dir(datetime))

datetime class

The datetime class gives Python developers the ability to manipulate date and time. To use the datetime class in our Python program, we need to import it from the datetime module. Let’s write a simple Python program to print the time and date using the Python datetime module:

from datetime import datetime
# create a variable
todays_date = datetime.now()
print(todays_date)

The code above will print the current time, including year, month, date, hour, minute, and second.

Working with strings

The Python datetime module has two built-in methods, strptime() and strftime(), which help Python programmers convert or parse the time string to an object and the Python string time to DateTime object, respectively. Let’s review these.

strptime()

The strptime() method converts string date and time data into a DateTime object. The code below illustrates how to use these methods in Python:

from datetime import datetime
date_in_string = ‘2021-11-19’
convert_date_to_object = datetime.strptime(date_in_string, ‘%Y-%m-%d’)
print(convert_date_to_object)

In the code above, the strptime function takes two arguments, the date_in_string variable and a second string that shows a format or a placeholder demonstrating how the first variable should be represented.

The following list shows the various formats for representing the Python DateTime variables:

%a:  abbreviated weekday as Sun, Mon
%A:  weekdays full name 
%w:  weekdays as number
%d:  days in number and zero-padded 01, 02
%b:  Months abbreviate as Apr, Jun
%B:  Months full name April, June
%m:  months in number and zero-padded 03, 06
%y:   Year without century 21, 20, 19
%Y:  Year with century 2021, 2020, 2019
%H:  24 hours clock 00 - 23 zero-padded
%I:   12 hours clock 01 - 12 zero-padded
%p:   Period of the day as AM/PM
%M:  Minutes from 00 - 59 zero-padded
%s:   seconds from 00 - 59 zero-padded
%f:    microseconds 6 decimal places

To confirm that the output is an object, use the type function by running the following code:

print(type(convert_date-to_object))

strftime()

The strftime() method converts DateTime objects to strings. The code below illustrates how to use the strftime() method in Python:

from datetime import datetime
time_as_object = datetime.today()
print(time_as_object)
# to check the type use the code below
print(type(time_as_object))
# convert time_as_object to string
time_as_string = time_as_object.strftime(“%Y-%m-%d %H:%M:%S”)
print(time_as_string)
# to add the milliseconds use .%f
time_as_string = time_as_object.strftime(“%Y-%m-%d %H:%M:%S.%f”)
print(time_as_string)
# check type
print(type(time_as_string))

Note: There are more formats available that I did not include here. You can refer to the list above and try out different formats for practice.

date object: Extract day of the week and day of the month

The Python date object represents the date as year, month, and day. In this section, we’ll extract the day of the week, day of the month, and the year from the date class. We’ll also get the name of the day using the calendar module.

The Python programming language starts counting the day of the week from Monday. As a general programming rule, the first day starts from index 0.

Before we extract the content of the date class, let’s illustrate how Python reads days of the week with the following code snippet:

import calendar
for i in calendar.day_name:
        print(i)
# i represent items in calendar.day_name

The result of the program above is as follows:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

With this detail out of the way, we can start extracting days and the month from date. The code snippet below illustrates how to extract the various components:

from datetime import datetime
import calendar
day_variable = datetime.now
print(day_variable)
# this will print year, month, date and the time the code was run

# to print index of day of the week
print(day_variable.weekday)

# to print the date
print(day_variable.day)

# to print the month in number
print(day_variable.month)

# to print the year
print(day_variable.year)

# to print the name of the day
print(calendar.day_name[day_variable.weekday()])

time object: Extract hours, minutes, and seconds

The time object is a class in the Python datetime module that represents the local time of the day. Let’s see how to extract hour, minutes, and second components from the time class. The Python time constructor takes some optional arguments, with the most commonly used being hour, minutes, seconds, and milliseconds.



The code snippet below illustrates how to use the Python time object:

from datetime import time

# instantiate a new time object
time_variable = time()

# extract its component
print('The hour is: ', time_variable.hour)

print('The miniute: ', time_variable.minute)

print('The second is: ', time_variable.second)

The result of the code above is as follows:

0 
0 
0. 

The code above represents the default value of hour, minute, and second in the Python time class. Let’s go ahead and instantiate a constructor that takes three arguments:

from datetime import time

# instantiate a new time object
time = time(7, 57, 5)

# extract its component
print(“The hour is:  ”,  time.hour)
print(“The minute is: ”,  time.minute)
print(“The second is:  ”,  time.second)

The result of the code above will be:

The hour is: 7
The minute is: 57
The second is: 5

In the example above, we hardcoded the values, but we’ll need to write a program that takes the local time from your computer. Then, we’ll extract the time component following the example below:

from datetime import datetime
import calendar

time = datetime.now()

# print year, month, day, and time (hour, minute, seconds, and microseconds)
print(time.today())

# extract the component by printing them out
print(time.year)

# this will print the current year
# print the month
print(time.month)

# print the index of the day of the week
print(time.weekday())

# print the date of the month in a number format
print(time.day)

# print the name of the day of the month
print(calendar.day_name[time.weekday()])

tzinfo: Working with time zone information

You might recall that the Python datetime module is necessary due to variation or differences in time zone. datetime.now() uses the time on the computer since it doesn’t have any information about the time zone.

Suppose a developer is working on a project with a global audience and they need to display the time based on the user’s time zone. Python provides a very useful module for handling cases like this, the pytz module.

The pytz module helps developers to handle time zone conversions. The code snippet below illustrates how to use the Python pytz module:

from datetime import datetime
import pytz

# get the local time
local_time = datetime.now()
print(“Local time is: “, local_time)

tz_Lagos = pytz.timezone(‘Africa/Lagos’)
datetime_in_Lagos = datetime.now(tz_Lagos)
print(datetime_in_Lagos)

# use f string and print timezone and time together
print(f‘ Time in {tz_Lagos} is {datetime_in_Lagos}’)

Depending on where you are on the globe, you can use this Python module and print the time of any time zone. For instance, I am in Lagos, Africa, and I want to print the current time in Moscow, Europe. I can do so using the code snippet below:

from datetime import datetime
import pytz

timeZone_in_Moscow = pytz.timezone(‘Europe/Moscow’)
datetime_in_Moscow = datetime.now(timeZone_in_Moscow)
print(datetime_in_Moscow)

The program will print the current time in Moscow to the console, even though I’m in Africa. Now that we know how to get the time in different time zones, let’s talk about timedelta.

Python timedelta object

The Python timedelta is an object that represents the time duration, which is the difference between two times or dates. Found in the Python datetime module, timedelta takes optional arguments with all initial values set to zero.

To get the differences between two times or dates, we first need to import timedelta:

# import timedelta 
from datetime import timedelta, datetime

# get current time
today = datetime.now()

# create a timedelta
weeks_ago = timedelta(weeks=4)

# print the difference between today and 4 weeks ago

difference = today - week_ago
print(difference)

The timedelta object can take the following parameters: weeks, seconds, minutes, milliseconds, microseconds, hours, and days. The result of the code above will vary based on when you run the program.

Understanding the tzinfo class

tzinfo, another class in the Python datetime module, is useful while processing details about a particular time zone. The Python tzinfo class is an abstract class, so it can’t be instantiated.

To implement the various methods in this class, a concrete subclass has to be derived from it. The instance of tzinfo can now be passed into the datetime and time constructor objects. Some of the methods present in the tzinfo class are listed below:

  1. utcoffset(dt): Returns the offset of local time from UTC as a timedelta object
  2. dst(dt): Returns None if the daylight saving time isn’t available. Otherwise, it returns the daylight saving time as timedelta object
  3. tzname(dt): Returns the corresponding datetime object time zone name as a string

Python datetime module example application

Let’s use the information we’ve covered so far to build a birthday calculator, which will print the user’s current age and a countdown to their next birthday. The countdown will include the number of days, hours, minutes, and seconds remaining before their next birthday, as well as the day of the week their birthday falls on. Our birthday calculator takes the user’s birthday as input on Line 20:

import calendar
import datetime
# the neccessary modules we need

current_time_and_date = datetime.datetime.now()
# access the current date and time

# access today name
today_name = calendar.day_name[current_time_and_date.weekday()]

# declare a time object
class Time(object):
  current_time_and_date = datetime.now()

  def __init__(self, year=1, month=1, day=1, hour=0, minute=0, second=0):
        self.date = datetime.datetime(year, month, day, hour, minute, second

# initialize two variables to hold today's date and the birthday respectively
today = Time().current_time_and_date
birthday = Time(1960, 12, 4).date

# declare a function that returns today using f-string

def name_of_day_of_the_week():
  return f'Today is {today_name}'

# declare a function that receives birthday as an argument

def birthday_records(birthday_param):
  age = today.year - birthday_param.year

  if (birthday_param.month == today.month) and (birthday_param.day <= today.day):
      pass
  elif birthday_param.month < today.month:
      pass
  else
      age = age - 1


  birthday_now = Time(today.year, birthday_param.month, birthday_param.day).date

  next_birthday = str(birthday_now - today).split()

  if len(next_birthday) > 1:
      days = int(next_birthday[0])
      time = next_birthday[2].split(":")

  else:
      days = 365
      time = next_birthday[0].split(":")


  hours = [0]
  minutes = [1]
  seconds = \[2\][:2]

  if days < 0 and days != 365:
      days += 365

  elif days == 365:
        days = 0

  else:
      days = days



print("2 You are %s years old; and is next birthday is %sd:%sh:%sm:%ss" & (age, days, hours, minutes, seconds))

#invoke the necessary functions

print(name_of_day_of_the_week())
birthday_records(birthday)

Conclusion

In this tutorial, we learned how to handle dates and times using the Python datetime module.
We also covered how to use the various classes made available by the Python datetime module. Finally, we put our knowledge to use by building an example application that counts down the days, minutes, and seconds until the user’s next birthday.

Handling dates and times in Python is not always straightforward. In this article, we learned how to simplify the process using the Python datetime module. Hopefully, this article provided some clarifications to help you get started. Be sure to leave a comment if you have any questions.


More great articles from LogRocket:


 

: Full visibility into your web and mobile apps

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps.

.
Frank Joseph I'm an innovative software engineer and technical writer passionate about the developer community. I'm interested in building applications that run on the internet.

Leave a Reply