Handling Dates and Times in Python
Posted on June 1, 2024 (Last modified on June 8, 2024) • 2 min read • 215 wordsLearn to handle dates and times in Python using the `datetime` module, including parsing, formatting, and performing arithmetic operations on dates.
Managing dates and times is crucial for many applications. This guide covers the datetime
module for parsing, formatting, and performing arithmetic operations on dates and times in Python.
from datetime import datetime
date_str = "2024-06-14"
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
print(date_obj) # Output: 2024-06-14 00:00:00
formatted_date = date_obj.strftime("%B %d, %Y")
print(formatted_date) # Output: June 14, 2024
now = datetime.now()
print(now)
specific_date = datetime(2024, 6, 14, 15, 30)
print(specific_date)
from datetime import timedelta
tomorrow = now + timedelta(days=1)
print(tomorrow)
yesterday = now - timedelta(days=1)
print(yesterday)
difference = tomorrow - now
print(difference.days) # Output: 1
from datetime import timezone
utc_time = datetime.now(timezone.utc)
print(utc_time)
local_time = utc_time.astimezone()
print(local_time)
Time zones can be managed using third-party libraries like pytz
.
from datetime import datetime
import pytz
utc = pytz.utc
est = pytz.timezone('US/Eastern')
utc_dt = datetime.now(utc)
est_dt = utc_dt.astimezone(est)
print(est_dt)
Effective date and time management is essential for many applications. Practice using the datetime
module to parse, format, and perform arithmetic operations on dates and times in Python.