Working with dates in Python can be done using the built-in datetime module. This module provides several classes for working with dates and times, including date, time, datetime, timedelta, and tzinfo.
The date class represents a date (year, month, day) and provides methods for working with dates, such as formatting and arithmetic. The datetime class represents a date and time (year, month, day, hour, minute, second, microsecond) and provides similar methods for working with dates and times.
Here are some examples of working with dates using the datetime module:
import datetime# create a date object for today's datetoday = datetime.date.today()print(today) # 2023-03-14# create a datetime object for a specific date and timedt = datetime.datetime(2023, 3, 14, 12, 30, 0)print(dt) # 2023-03-14 12:30:00# format a date as a stringdate_str = today.strftime('%Y-%m-%d')print(date_str) # 2023-03-14# parse a string as a datedate_str = '2023-03-14'date = datetime.datetime.strptime(date_str, '%Y-%m-%d').date()print(date) # 2023-03-14# perform arithmetic with datestomorrow = today + datetime.timedelta(days=1)print(tomorrow) # 2023-03-15# compare datesif tomorrow > today: print('Tomorrow is later than today') |
There are many more methods available for working with dates and times in Python, and the datetime module provides a powerful and flexible way to work with dates and times in your code.