Working with Dates, Times, and Timedeltas
Working with Dates
The date
class in the datetime
module represents a specific date, without any time information. You can create a date
object using the date()
constructor:
import datetime
## Create a date object
today = datetime.date(2023, 5, 1)
print(today) ## Output: 2023-05-01
You can also use the today()
method to get the current date:
today = datetime.date.today()
print(today) ## Output: 2023-05-01
Working with Times
The time
class in the datetime
module represents a specific time, without any date information. You can create a time
object using the time()
constructor:
import datetime
## Create a time object
current_time = datetime.time(14, 30, 0)
print(current_time) ## Output: 14:30:00
Working with Datetimes
The datetime
class in the datetime
module represents a specific date and time. You can create a datetime
object using the datetime()
constructor:
import datetime
## Create a datetime object
now = datetime.datetime(2023, 5, 1, 14, 30, 0)
print(now) ## Output: 2023-05-01 14:30:00
You can also use the now()
method to get the current date and time:
now = datetime.datetime.now()
print(now) ## Output: 2023-05-01 14:30:00
Working with Timedeltas
The timedelta
class in the datetime
module represents a time interval. You can create a timedelta
object using the timedelta()
constructor:
import datetime
## Create a timedelta object
two_hours = datetime.timedelta(hours=2)
print(two_hours) ## Output: 2:00:00
You can perform various operations with timedelta
objects, such as adding or subtracting them from date
or datetime
objects.
import datetime
## Add a timedelta to a datetime
future_datetime = now + two_hours
print(future_datetime) ## Output: 2023-05-01 16:30:00
By understanding these basic concepts and operations, you can start working with dates, times, and time intervals in your Python applications.