DEV Community

Cover image for Datetime Manipulation in Python
≀Paulo Portela
≀Paulo Portela

Posted on • Updated on

Datetime Manipulation in Python

Introduction

In the realm of programming, dealing with dates and times is a ubiquitous task. Python's datetime module equips developers with powerful tools to manage temporal data effortlessly. In this chapter, we will explore various functionalities of the datetime module through practical examples, focusing on mathematical operations involving dates and times.

Getting Started

Getting the Current Date and Time

To retrieve the current date and time, we can use the datetime class from the datetime module.

import datetime

current_date = datetime.datetime.now()
print(current_date)
Enter fullscreen mode Exit fullscreen mode

Output:

2024-02-25 02:12:20.041862
Enter fullscreen mode Exit fullscreen mode

Getting the Current Date in UTC

To obtain the current date and time in Coordinated Universal Time (UTC), we can utilize the UTC.

import datetime

current_datetime_utc = datetime.datetime.now(tz=datetime.UTC)
print(current_datetime_utc)
Enter fullscreen mode Exit fullscreen mode

Output:

2024-02-25 02:13:05.223959+00:00
Enter fullscreen mode Exit fullscreen mode

Converting String to Date

Suppose we have a string representing a date, we can convert it to a datetime object using strptime() method.

import datetime

date_string = "2024-02-25"
converted_date = datetime.datetime.strptime(date_string, "%Y-%m-%d")
print(converted_date)
Enter fullscreen mode Exit fullscreen mode

Output:

2024-02-25 00:00:00
Enter fullscreen mode Exit fullscreen mode

Converting Datetime to String

Conversely, if we have a datetime object, we can convert it to a string with strftime() method.

import datetime

formatted_datetime = datetime.datetime.now().strftime(format="%Y-%m-%d")
print(formatted_datetime)
Enter fullscreen mode Exit fullscreen mode

Output:

2024-02-25
Enter fullscreen mode Exit fullscreen mode

Date Manipulation

Getting Current Year

To fetch the current year, we can access the year attribute of a datetime object.

import datetime

current_year = datetime.date.today().year
print(current_year)
Enter fullscreen mode Exit fullscreen mode

Output:

2024
Enter fullscreen mode Exit fullscreen mode

Getting the First Day of the Current Month

We can retrieve the first day of the current month by replacing the day part of the current date.

import datetime

first_day_of_month = datetime.date.today().replace(day=1)
print(first_day_of_month)
Enter fullscreen mode Exit fullscreen mode

Output:

2024-02-01
Enter fullscreen mode Exit fullscreen mode

Getting the First Day of the Previous Month

Similarly, to obtain the first day of the previous month, we can manipulate the date accordingly.

import datetime

first_day_of_previous_month = (datetime.date.today().replace(day=1) - datetime.timedelta(days=1)).replace(day=1)
print(first_day_of_previous_month)
Enter fullscreen mode Exit fullscreen mode

Output:

2024-01-01
Enter fullscreen mode Exit fullscreen mode

Getting the Last Day of the Previous Month

To find the last day of the previous month, we can first find the first day of the current month and then subtract one day.

import datetime

last_day_of_previous_month = datetime.date.today().replace(day=1) - datetime.timedelta(days=1)
print(last_day_of_previous_month)
Enter fullscreen mode Exit fullscreen mode

Output:

2024-01-31
Enter fullscreen mode Exit fullscreen mode

Day-of-Week Operations

Getting the Current Weekday

The weekday() method returns the day of the week as an integer, where Monday is 0 and Sunday is 6.

import datetime

current_weekday = datetime.date.today().weekday()
print(current_weekday)
Enter fullscreen mode Exit fullscreen mode

Output:

6
Enter fullscreen mode Exit fullscreen mode

Getting the Current Day

To obtain the day of the month from a datetime object, we can access its day attribute.

import datetime

current_day = datetime.date.today().day
print(current_day)
Enter fullscreen mode Exit fullscreen mode

Output:

25
Enter fullscreen mode Exit fullscreen mode

Getting the Previous Day

To find the date for the previous day, we can subtract one day from the current date.

import datetime

previous_day = datetime.date.today() - datetime.timedelta(days=1)
print(previous_day)
Enter fullscreen mode Exit fullscreen mode

Output:

2024-02-24
Enter fullscreen mode Exit fullscreen mode

Getting the Sunday from the Current Week

To get the date for the Sunday of the current week, we need to subtract the current weekday from the current date.

import datetime

sunday_current_week = datetime.date.today() + datetime.timedelta(days=-datetime.date.today().weekday() - 1, weeks=0)
print(sunday_current_week)
Enter fullscreen mode Exit fullscreen mode

Output:

2024-02-18
Enter fullscreen mode Exit fullscreen mode

Getting Monday from the Current Week

Similarly, to find the Monday of the current week, we need to adjust the date accordingly.

import datetime

monday_current_week = datetime.date.today() + datetime.timedelta(days=-datetime.date.today().weekday(), weeks=0)
print(monday_current_week)
Enter fullscreen mode Exit fullscreen mode

Output:

2024-02-19
Enter fullscreen mode Exit fullscreen mode

Getting Monday from the Previous Week

To find the Monday of the previous week, we can subtract seven days from the current Monday.

import datetime

monday_previous_week = datetime.date.today() + datetime.timedelta(days=-datetime.date.today().weekday(), weeks=-1)
print(monday_previous_week)
Enter fullscreen mode Exit fullscreen mode

Output:

2024-02-12
Enter fullscreen mode Exit fullscreen mode

Date Comparison and Execution Time

Getting the Difference Between Two Dates

To calculate the difference between two dates, we simply subtract one from the other.

import datetime

date1 = datetime.datetime(year=2024, month=2, day=20)
date2 = datetime.datetime(year=2024, month=2, day=25)
difference = date2 - date1
print(difference.days)
Enter fullscreen mode Exit fullscreen mode

Output:

5
Enter fullscreen mode Exit fullscreen mode

Getting the Execution Time of Code

To measure the execution time of a piece of code, we can use the time module.

import math
import time

start_time = time.time()

# Code to measure execution time
math.factorial(100_000)

end_time = time.time()
execution_time = end_time - start_time
print(f"{execution_time} seconds")
Enter fullscreen mode Exit fullscreen mode

Output:

0.11599612236022949 seconds
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this chapter, we delved into the versatility of Python's datetime module for handling various temporal operations. Whether it's simple date arithmetic or complex time-sensitive calculations, the datetime module equips programmers with the tools needed to tackle any temporal challenge.

Top comments (0)