Posted by Kosal
Working with dates and times in Python can be accomplished using the datetime
module, which provides classes for manipulating dates and times. Here's a basic guide on how to work with dates and times in Python:
Import the datetime
module:
import datetime
Creating a Date or Time:
You can create date, time, or datetime objects using the date
, time
, and datetime
classes respectively.
# Create a date object
date_object = datetime.date(2024, 3, 13)
# Create a time object
time_object = datetime.time(14, 30, 0)
# Create a datetime object
datetime_object = datetime.datetime(2024, 3, 13, 14, 30, 0)
Getting the Current Date and Time:
You can get the current date and time using datetime.now()
method.
current_datetime = datetime.datetime.now()
Formatting Dates and Times:
You can format dates and times into strings using the strftime()
method.
formatted_date = date_object.strftime("%Y-%m-%d")
formatted_time = time_object.strftime("%H:%M:%S")
formatted_datetime = datetime_object.strftime("%Y-%m-%d %H:%M:%S")
Parsing Dates and Times:
You can parse strings into date, time, or datetime objects using the strptime()
method.
parsed_date = datetime.datetime.strptime("2024-03-13", "%Y-%m-%d")
Manipulating Dates and Times:
You can perform arithmetic operations on dates and times using timedelta objects.
# Add 1 day to a date
new_date = date_object + datetime.timedelta(days=1)
# Subtract 1 hour from a datetime
new_datetime = datetime_object - datetime.timedelta(hours=1)
Comparing Dates and Times:
You can compare dates and times using comparison operators (<
, >
, ==
, etc.).
if date_object1 > date_object2:
print("Date 1 is later than Date 2")
These are the basic operations you can perform with dates and times in Python using the datetime
module. Depending on your specific needs, you may need to explore additional functionality provided by this module or other related libraries like dateutil
or arrow
.