๐Ÿ“ Python

The datetime Module: Working with Dates and Times

P
Author
PyLand Team
๐Ÿ“…
Published
08.05.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
379
๐ŸŒฟ
Level
Medium

datetime is Python’s standard module for working with dates and times. It’s part of the standard library โ€” no installation needed.

Import

from datetime import datetime, date, timedelta

Current Date and Time

from datetime import datetime

now = datetime.now()
print(now)              # 2025-05-07 14:32:15.123456
print(now.year)         # 2025
print(now.month)        # 5
print(now.day)          # 7
print(now.hour)         # 14

Formatting โ€” strftime()

strftime() converts a datetime object to a string using a format template:

from datetime import datetime

now = datetime.now()
print(now.strftime('%d.%m.%Y'))        # 07.05.2025
print(now.strftime('%d.%m'))           # 07.05
print(now.strftime('%H:%M'))           # 14:32
print(now.strftime('%d.%m.%Y %H:%M')) # 07.05.2025 14:32

Format codes:

Code Meaning Example
%d Day 07
%m Month 05
%Y Year (4 digits) 2025
%H Hour (24h) 14
%M Minutes 32

Parsing a String โ€” strptime()

The reverse operation: string โ†’ datetime:

from datetime import datetime

dt = datetime.strptime('2025-05-07', '%Y-%m-%d')
print(dt.year)   # 2025
print(dt.month)  # 5

Unix Timestamp โ€” fromtimestamp()

A Unix timestamp is the number of seconds since January 1, 1970. Many APIs return time in this format (e.g., the dt field in OpenWeatherMap).

from datetime import datetime

timestamp = 1735689600  # number from an API
dt = datetime.fromtimestamp(timestamp)
print(dt)                          # 2025-01-01 00:00:00
print(dt.strftime('%d.%m.%Y'))    # 01.01.2025
print(dt.strftime('%d.%m'))       # 01.01

fromtimestamp() automatically accounts for your system’s timezone.

Comparing Dates

from datetime import date

today = date.today()
some_day = date(2025, 1, 1)

print(today > some_day)   # True
diff = today - some_day
print(diff.days)          # number of days between the dates

timedelta โ€” Shifting Dates

from datetime import date, timedelta

today = date.today()
tomorrow = today + timedelta(days=1)
week_later = today + timedelta(days=7)

print(tomorrow)     # tomorrow's date
print(week_later)   # date one week from now

Practical Example: Filtering by Date

from datetime import datetime

items = [
    {'dt': 1735689600, 'temp': -3},
    {'dt': 1735776000, 'temp': -1},
    {'dt': 1735862400, 'temp':  2},
]

seen_dates = set()
for item in items:
    dt = datetime.fromtimestamp(item['dt'])
    date_str = dt.strftime('%d.%m')

    if date_str in seen_dates:
        continue
    seen_dates.add(date_str)

    print(f"{date_str}: {item['temp']}ยฐC")

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

if __name__ == "__main__": the Python entry point

The if name == "main" guard defines a Python program's entry point: it distinguishes direct...

๐Ÿ“… 14.08.2026 ๐Ÿ‘๏ธ 44
๐Ÿ“

strip() and lower(): Preparing User Text ๐Ÿงน

A user may enter the correct word with extra spaces or different letter case. Python...

๐Ÿ“… 11.08.2026 ๐Ÿ‘๏ธ 50
๐Ÿ“

ord(), chr(), and Cyclic Letter Shifts in Python ๐Ÿ”

A string contains characters, but a computer stores every character as a numeric code. Python...

๐Ÿ“… 09.08.2026 ๐Ÿ‘๏ธ 89
๐ŸŽ“ Continue learning

Courses that cover this material

Visit the course to apply this material in practice.

API in Practice: Interact with Any Service Open course curriculum