Datetime Manipulation in Python
Published: 2024-02-25 01:28:24

# 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.

```python
import datetime

current_date = datetime.datetime.now()
print(current_date)
```

Output:
```plaintext
2024-02-25 02:12:20.041862
```

## Getting the Current Date in UTC

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

```python
import datetime

current_datetime_utc = datetime.datetime.now(tz=datetime.UTC)
print(current_datetime_utc)
```

Output:
```plaintext
2024-02-25 02:13:05.223959+00:00
```

## Converting String to Date

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

```python
import datetime

date_string = "2024-02-25"
converted_date = datetime.datetime.strptime(date_string, "%Y-%m-%d")
print(converted_date)
```

Output:
```plaintext
2024-02-25 00:00:00
```

## Converting Datetime to String

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

```python
import datetime

formatted_datetime = datetime.datetime.now().strftime(format="%Y-%m-%d")
print(formatted_datetime)
```

Output:
```plaintext
2024-02-25
```

# Date Manipulation

## Getting Current Year

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

```python
import datetime

current_year = datetime.date.today().year
print(current_year)
```

Output:
```plaintext
2024
```

## 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.

```python
import datetime

first_day_of_month = datetime.date.today().replace(day=1)
print(first_day_of_month)
```

Output:
```plaintext
2024-02-01
```

## Getting the First Day of the Previous Month

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

```python
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)
```

Output:
```plaintext
2024-01-01
```

## 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.

```python
import datetime

last_day_of_previous_month = datetime.date.today().replace(day=1) - datetime.timedelta(days=1)
print(last_day_of_previous_month)
```

Output:
```plaintext
2024-01-31
```

# 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.

```python
import datetime

current_weekday = datetime.date.today().weekday()
print(current_weekday)
```

Output:
```plaintext
6
```

## Getting the Current Day

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

```python
import datetime

current_day = datetime.date.today().day
print(current_day)
```

Output:
```plaintext
25
```

## Getting the Previous Day

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

```python
import datetime

previous_day = datetime.date.today() - datetime.timedelta(days=1)
print(previous_day)
```

Output:
```plaintext
2024-02-24
```

## 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.

```python
import datetime

sunday_current_week = datetime.date.today() + datetime.timedelta(days=-datetime.date.today().weekday() - 1, weeks=0)
print(sunday_current_week)
```

Output:
```plaintext
2024-02-18
```

## Getting Monday from the Current Week

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

```python
import datetime

monday_current_week = datetime.date.today() + datetime.timedelta(days=-datetime.date.today().weekday(), weeks=0)
print(monday_current_week)
```

Output:
```plaintext
2024-02-19
```

## Getting Monday from the Previous Week

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

```python
import datetime

monday_previous_week = datetime.date.today() + datetime.timedelta(days=-datetime.date.today().weekday(), weeks=-1)
print(monday_previous_week)
```

Output:
```plaintext
2024-02-12
```

# 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.

```python
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)
```

Output:
```plaintext
5
```

## Getting the Execution Time of Code

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

```python
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")
```

Output:
```plaintext
0.11599612236022949 seconds
```

# 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.