Working with Dates and Times
Working with dates and times is made easy with the built-in datetime module. Here's a quick guide on how to work with dates and times:
1. Import the datetime module:
Python Code
import datetime
2. Create Date Objects:
can create date objects using the datetime.date() constructor. Pass the year, month, and day as arguments:
Python Code
# Create a date object for January 1, 2024
date_obj = datetime.date(2024, 1, 1)
print(date_obj) # Output: 2024-01-01
3. Create Time Objects:
can create time objects using the datetime.time() constructor. Pass the hour, minute, second, and microsecond as arguments:
Python Code
# Create a time object for 8:30:00 AM
time_obj = datetime.time(8, 30)
print(time_obj) # Output: 08:30:00
4. Create DateTime Objects:
can create datetime objects using the datetime.datetime() constructor. Pass the year, month, day, hour, minute, second, and microsecond as arguments:
Python Code
# Create a datetime object for May 7, 2024, 8:30:00 AM
datetime_obj = datetime.datetime(2024, 5, 7, 8, 30)
print(datetime_obj) # Output: 2024-05-07 08:30:00
5. Get Current Date and Time:
can get the current date and time using datetime.datetime.now():
Python Code
current_datetime = datetime.datetime.now()
print(current_datetime) # Output: Current date and time
6. Format Dates and Times:
can format date and time objects using the strftime() method with formatting codes:
Python Code
formatted_date = datetime_obj.strftime('%Y-%m-%d')
formatted_time = datetime_obj.strftime('%H:%M:%S')
print(formatted_date) # Output: 2024-05-07
print(formatted_time) # Output: 08:30:00
7. Parse Strings to Dates:
can parse strings to date objects using strptime():
Python Code
date_str = '2024-05-07'
parsed_date = datetime.datetime.strptime(date_str, '%Y-%m-%d').date()
print(parsed_date) # Output: 2024-05-07
8. Perform Date Arithmetic:
can perform arithmetic operations on dates:
Python Code
# Add 5 days to a date
new_date = date_obj + datetime.timedelta(days=5)
print(new_date) # Output: 2024-01-06
9. Time Zones:
For time zone handling, consider using the pytz module or the timezone class from the datetime module.
These are some of the basics to get you started with working with dates and times . Let me know if you need more specific information!