The datetime
module in Python provides a wide range of functions and classes for working with dates and times. Here are some additional methods and functionality of the datetime
module along with examples:
1. Date Formatting and Parsing:
datetime.datetime.strptime(date_string, format)
: Parse a string representing a date and time according to the given format.
from datetime import datetime
date_str = "2023-07-21"
date_format = "%Y-%m-%d"
date_obj = datetime.strptime(date_str, date_format)
print("Parsed Date:", date_obj)
2. Date Arithmetic:
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
: Represents a duration of time.
You can perform arithmetic operations with timedelta
objects to add or subtract time from a datetime
object.
from datetime import datetime, timedelta
now = datetime.now()
one_week_later = now + timedelta(weeks=1)
print("One week later:", one_week_later)
3. Comparing Dates:
You can compare datetime
objects to determine which date is earlier or later.
from datetime import datetime
date1 = datetime(2023, 7, 21)
date2 = datetime(2023, 8, 15)
if date1 < date2:
print("date1 is earlier than date2")
else:
print("date2 is earlier than date1")
4. Date and Time Formatting:
datetime.strftime(format)
: Format a datetime
object as a string using the specified format.
from datetime import datetime
now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted Date:", formatted_date)
5. Time Zones:
Python's datetime
module does not provide built-in time zone support. You can use third-party libraries like pytz
for working with time zones.
from datetime import datetime
import pytz
utc_now = datetime.now(pytz.utc)
eastern_time = utc_now.astimezone(pytz.timezone("US/Eastern"))
print("Eastern Time:", eastern_time)
6. Date Arithmetic (Using timedelta):
You can perform arithmetic operations with timedelta
objects to add or subtract time from a datetime
object.
from datetime import datetime, timedelta
now = datetime.now()
one_week_later = now + timedelta(weeks=1)
print("One week later:", one_week_later)
These are some additional methods and functionality provided by the datetime
module for working with dates and times in Python. The module is versatile and crucial for tasks involving date manipulation, formatting, and parsing.