Working with dates and times is essential in many applications, from scheduling tasks to logging events. Python provides powerful built-in modules, datetime
and date
, to handle date and time operations efficiently. In this guide, we will explore how to use these modules effectively with real-world examples.
1 Python datetime
Module
1.1 Getting Current Date and Time
from datetime import datetime,timezone
now = datetime.now()
print("Current Date and Time:", now) #Current Date and Time: 2025-03-07 14:30:45.123456
# Get the current time in UTC (with timezone info)
# current_datetime_utc = datetime.now(timezone.utc)
1.2 Creating a Specific Date and Time
You can create a specific date and time using the datetime
constructor:
custom_date = datetime(2024, 5, 15, 10, 30, 0)
print("Custom Date and Time:", custom_date) # Custom Date and Time: 2024-05-15 10:30:00
1.3 Formatting Date and Time
Use strftime()
to format date and time as a string:
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted Date:", formatted_date)
# Construct a date from a string in ISO 8601 format.
current_datetime_utc = '2025-03-04T11:00:16.645+00:00'
utc_time = datetime.fromisoformat(current_datetime_utc)
Common Format Codes:
Code | Meaning |
---|---|
%Y | Year (2024) |
%m | Month (01-12) |
%d | Day (01-31) |
%H | Hour (00-23) |
%M | Minute (00-59) |
%S | Second (00-59) |
1.4 Parsing a Date String
Use strptime()
to convert a string into a datetime object:
date_str = "2024-05-15 10:30:00"
parsed_date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print("Parsed Date:", parsed_date)
2. Python date
Module
The date
class is a simpler version of datetime
, dealing only with dates.
2.1 Getting Today’s Date
from datetime import date
today = date.today()
print("Today's Date:", today)
2.2 Creating a Specific Date
custom_date = date(2025, 8, 20)
print("Custom Date:", custom_date)
2.3 Extracting Year, Month, and Day
print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)
3. TimeDelta – Date Arithmetic
timedelta
allows you to perform arithmetic on dates.
from datetime import timedelta
yesterday = today - timedelta(days=1)
tomorrow = today + timedelta(days=1)
print("Yesterday:", yesterday)
print("Tomorrow:", tomorrow)
You can also calculate differences between two dates:
future_date = date(2025, 12, 31)
difference = future_date - today
print("Days Until New Year 2026:", difference.days)
4. Handling Time Zones with pytz
To work with time zones, install pytz
:
pip install pytz
4.1 Setting a Specific Time Zone
import pytz
timezone = pytz.timezone("Asia/Kathmandu")
kathmandu_time = datetime.now(timezone)
print("Kathmandu Time:", kathmandu_time)
from datetime import datetime
import pytz
utc_time = datetime.now()
local_timezone = pytz.timezone("Asia/kathmandu")
local_time = utc_time.astimezone(local_timezone)
print(local_time)