Working with Dates and Times in Python (datetime module)

3D isometric illustration of interlocking clock gears and a digital calendar, representing Python's datetime module.

If you’re not using Pandas, Python’s built-in datetime module is the standard way to handle dates and times. The Python datetime module offers essential functionality for date and time manipulation in your scripts.

First open Terminal :

import datetime

1. Getting the Current Time

now = datetime.datetime.now()
print(now)
# Output: 2025-12-12 05:30:15.123456

2. Formatting a Date (strftime)

This turns a datetime object into a clean string. (strftime = string from time)

# %Y = YYYY, %m = mm, %d = dd, %H = 24hr, %M = min
formatted = now.strftime("%Y-%m-%d %H:%M")
print(formatted)
# Output: 2025-12-12 05:30

3. Parsing a String (strptime)

This turns a string back into a datetime object. (strptime = string parse time)

date_string = "11/12/2025"
date_obj = datetime.datetime.strptime(date_string, "%m/%d/%Y")
print(date_obj)
# Output: 2025-12-12 00:00:00

4. Date Math (timedelta)

Need to figure out what the date was 7 days ago? Use timedelta.

one_week_ago = now - datetime.timedelta(days=7)
print(one_week_ago)

Similar Posts

Leave a Reply