Datetime
datetime
module is Python’s built-in library for handling dates, times, time zones, and formatting. It provides powerful features for manipulating and working with dates efficiently.
1. Importing the datetime
Module
import datetime
This gives access to various date and time classes:
- datetime.date
→ Handles only dates.
- datetime.time
→ Handles only times.
- datetime.datetime
→ Handles both date and time.
- datetime.timedelta
→ Represents time differences.
- datetime.timezone
→ Handles time zones (replacement for pytz
).
2. Working with Dates
The date
class handles year, month, and day.
A) Get Today’s Date
= datetime.date.today()
today print(today) # e.g., 2025-01-31
B) Create a Specific Date
= datetime.date(2025, 1, 31)
d print(d) # 2025-01-31
C) Extracting Date Components
print(d.year) # 2025
print(d.month) # 1
print(d.day) # 31
D) Formatting a Date
= d.strftime("%B %d, %Y")
formatted_date print(formatted_date) # January 31, 2025
Common Date Formats: -
%Y-%m-%d
→2025-01-31
-%B %d, %Y
→January 31, 2025
-%d/%m/%Y
→31/01/2025
3. Working with Time
The time
class handles hours, minutes, seconds, and microseconds.
A) Create a Specific Time
= datetime.time(14, 30, 45) # 14:30:45
t print(t) # 14:30:45
B) Extracting Time Components
print(t.hour) # 14
print(tDatetime.minute) # 30
print(t.second) # 45
C) Formatting Time
= t.strftime("%I:%M %p")
formatted_time print(formatted_time) # 02:30 PM (12-hour format)
4. Working with Date and Time Together
The datetime
class represents both date and time.
A) Get the Current Date & Time
= datetime.datetime.now()
now print(now) # 2025-01-31 14:30:45.123456
B) Create a Specific Date & Time
= datetime.datetime(2025, 1, 31, 14, 30, 45)
dt print(dt) # 2025-01-31 14:30:45
C) Extract Components
print(dt.year) # 2025
print(dt.month) # 1
print(dt.day) # 31
print(dt.hour) # 14
print(dt.minute) # 30
print(dt.second) # 45
D) Formatting Date & Time
= dt.strftime("%Y-%m-%d %H:%M:%S")
formatted_dt print(formatted_dt) # 2025-01-31 14:30:45
5. Time Differences with timedelta
A timedelta
represents a duration between two datetime objects.
A) Create a timedelta
= datetime.timedelta(days=5, hours=3, minutes=30)
delta print(delta) # 5 days, 3:30:00
B) Add/Subtract a timedelta
= today + delta
future_date print(future_date) # 2025-02-05
= today - delta
past_date print(past_date) # 2025-01-26
C) Difference Between Two Dates
= datetime.date(2025, 2, 10)
date1 = datetime.date(2025, 1, 31)
date2
= date1 - date2
difference print(difference.days) # 10
6. Handling Time Zones (datetime.timezone
)
Instead of using pytz
, Python has built-in timezone support using datetime.timezone
.
A) Get UTC Time
= datetime.datetime.now(datetime.timezone.utc)
utc_now print(utc_now) # 2025-01-31 12:00:00+00:00
B) Define a Fixed Offset Time Zone
To create a timezone with a fixed UTC offset:
= datetime.timedelta(hours=5, minutes=30) # UTC+5:30
offset = datetime.timezone(offset, name="IST")
ist
= datetime.datetime(2025, 1, 31, 14, 30, tzinfo=ist)
dt print(dt) # 2025-01-31 14:30:00+05:30
C) Convert Between Time Zones
= datetime.datetime.now(datetime.timezone.utc)
utc_now = datetime.timezone(datetime.timedelta(hours=5, minutes=30)) # UTC+5:30
ist
= utc_now.astimezone(ist)
ist_now print(ist_now) # Converts to IST timezone
7. Parsing Strings into datetime
(strptime
)
Convert a string into a datetime
object:
= "31-01-2025 14:30"
date_string = datetime.datetime.strptime(date_string, "%d-%m-%Y %H:%M")
dt print(dt) # 2025-01-31 14:30:00
8. Comparing Dates & Times
= datetime.date(2025, 1, 31)
d1 = datetime.date(2025, 2, 1)
d2
print(d1 < d2) # True
print(d1 == d2) # False
For datetime objects:
= datetime.datetime(2025, 1, 31, 12, 0)
dt1 = datetime.datetime(2025, 1, 31, 14, 0)
dt2
print(dt1 < dt2) # True
9. Generating Timestamps
A) Get the Current Unix Timestamp
= datetime.datetime.now().timestamp()
timestamp print(timestamp) # e.g., 1738293600.123456
B) Convert Timestamp to datetime
= datetime.datetime.fromtimestamp(1738293600)
dt_from_timestamp print(dt_from_timestamp)
10. Using datetime
in JSON Serialization
Python’s datetime
is not JSON serializable by default:
import json
= datetime.datetime.now()
now "timestamp": now}) # TypeError: Object of type datetime is not JSON serializable json.dumps({
Solution: Convert to String
"timestamp": now.isoformat()}) json.dumps({
Solution: Convert to Unix Timestamp
"timestamp": now.timestamp()}) json.dumps({
Summary
Feature | Code Example |
---|---|
Get Today’s Date | datetime.date.today() |
Get Current Time | datetime.datetime.now().time() |
Create a Date | datetime.date(2025, 1, 31) |
Create a Time | datetime.time(14, 30, 45) |
Get Date & Time | datetime.datetime.now() |
Format Date | .strftime("%Y-%m-%d") |
Convert String to Date | .strptime("31-01-2025", "%d-%m-%Y") |
Add 5 Days | date + timedelta(days=5) |
Get UTC Time | datetime.datetime.now(datetime.timezone.utc) |
Convert Time Zones | .astimezone(new_timezone) |
Conclusion
datetime
is Python’s built-in solution for working with dates and times.datetime.timezone
(notpytz
) provides native timezone handling.timedelta
helps add/subtract time.- String parsing (
strptime
) and formatting (strftime
) are essential for conversions. - Always consider time zones when working with global applications.
This guide covers everything you need to master datetime
! 🚀