howtouselinux

8 Time-Saving Tips to use Python Datetime Module

Table of Contents

The Python datetime module is a powerful tool that can be used to manipulate time data. It allows you to work with dates and times in a variety of ways, which can save you time when developing applications or scripts. In this blog post, we will discuss 10 tips for working with the Python time module. These tips will help you get the most out of this module and make your development process easier!

Use datetime objects instead of numbers when dealing with time

The first tip is to use datetime objects instead of numbers when dealing with time. This may seem obvious, but it can be easy to forget this simple rule! For example, don’t use “01/02/2021” as an input parameter for your program instead of using something like date(2020, 01, 02) .

# create a datatime obj
dt = datetime.datetime(2019, 2, 15)
# 1. Get the current day of the month
dt.day #> 31
# 2. Get the current day of the week
dt.isoweekday() #> 5 –> Friday
# 3. Get the current month of the year
dt.month #> 2 –> February
# 4. Get the Year
dt.year #> 2019

Use datetime module’s strftime() function

The second tip is to use the datetime module’s strftime() function. This will allow you to convert any datetime object to nearly any representation of date format! For example: time.strptime(“2020-01-02 15:00:00″, “%Y-%m-%d %H:%M:%S”) returns a datetime object with year = 2020, month = 01 and day = 02.

dt = datetime.datetime(2001, 1, 31, 10, 51, 0)
print(dt.strftime(‘%Y-%m-%d::%H-%M’))
#> 2001-01-31::10-51

Use the

Use datetime module’s timedelta() function

The third tip is to use the timedelta() function from Python’s built-in math module if you need an interval between two date objects (e.g., days). For example, you can calculate the number of days between January first and July fourth by subtracting them: >>> datetime.datetime(2020,7,4)-datetime.datetime(2020, 1, 1)
datetime.timedelta(days=185)

>>> td1 = datetime.timedelta(days=30) # 30 days
>>> td2 = datetime.timedelta(weeks=1) # 1 week
>>> td1 – td2
datetime.timedelta(days=23)

Convert UTC time zones into local time zones by adding timedelta objects

The fourth tip is that you can convert UTC time zones into local time zones by adding timedelta objects (e.g., timedelta(hours=-12)).

from datetime import datetime, timedelta
# Using current time
ini_time_for_now = datetime.now()
# printing initial_date
print (“initial_date”, str(ini_time_for_now))

# Calculating past dates
# for two years
past_date_before_2yrs = ini_time_for_now – timedelta(days = 730)
# for 8 hours
past_date_before_8hours = ini_time_for_now – timedelta(hours = 8)

Use datetime module’s strftime() function to get the current time

The fifth tip is to use the strftime() function from Python’s datetime module to format dates and times into strings. For example, you can create a string representation of the current date using: time.strftime(“%Y-%m-%d”) .

>>> from datetime import datetime
>>> now = datetime.now()
>>> print(“The current date is:”, now.strftime(“%Y-%m-%d %H:%M:%S”))
The current date is: 2022-02-20 10:19:14

Use datetime module’s now() function to get the data objects of current time

The sixth tip is to use the datetime.now() function to get the current date and time. This can be useful if you need to calculate elapsed times or other information based on the current timestamp.

>>> from datetime import datetime
>>> now = datetime.now()
datetime.datetime(2022, 2, 20, 11, 43, 43, 364551)

Use time module’s sleep() function to pause your program for a given number of seconds

The seventh tip is to use the Python time module’s sleep() function to pause your program for a given number of seconds. This can be helpful if you need to wait for a certain event to happen before continuing with your code.

import time
print(“Print now”)
time.sleep(4.2)
print(“Printing after 4.2 seconds”)

Use datetime module’s utcnow() function to get the current UTC time

The eighth tip is to use the time module’s utcnow() function to get the current UTC date and time. This can be useful if you need to calculate elapsed times or other information based on the current timestamp.

from datetime import datetime
datetime.utcnow()
datetime.datetime(2022, 2, 20, 11, 47, 35, 57672)

David Cao
David Cao

Hey there! I am David, a Cloud & DevOps Enthusiast and 18 years of experience as a Linux engineer. I work with AWS, Git & GitHub, Linux, Python, Ansible, and Bash. I am a technical blogger and a Software Engineer, enjoy sharing my learning and contributing to open-source.