To represent a date and time in Python, we can use the datetime
module which is part of the Python Standard Library.
The datetime
module provides classes for manipulating dates and times.
Here’s how you can create a date and time object:
1from datetime import datetime
2
3 # Creating a date and time object
4 current_time = datetime.now()
5
6 print(current_time)
When you run this code, it will output the current date and time in the format YYYY-MM-DD HH:MM:SS.ssssss
.
If you want to create a date and time object for a specific date and time, you can use the following code:
1 from datetime import datetime
2
3 # Creating a date and time object for a specific date and time
4 specific_time = datetime(2022, 1, 1, 12, 30, 45)
5
6 print(specific_time)
In this example, 2022
is the year, 1
is the month, 1
is the day, 12
is the hour, 30
is the minute, and 45
is the second.
If you want to perform operations on the date and time objects, you can use the following code:
1 from datetime import datetime, timedelta
2
3# Creating two date and time objects
4 date1 = datetime(2022, 1, 1, 12, 30, 45)
5 date2 = datetime(2022, 1, 2, 12, 30, 45)
6
7 # Calculating the difference between the two dates
8 difference = date2 - date1
9
10 print("Difference:", difference)
11
12 # Adding 5 days to the first date
13 new_date = date1 + timedelta(days=5)
14
15 print("New date:", new_date)
This code will output:
1Difference: 1 day, 0:00:00
2New date: 2022-01-06 12:30:45
These are just a few examples of how you can use the datetime
module in Python to represent and manipulate date and time.
About Author
Discover more from SURFCLOUD TECHNOLOGY
Subscribe to get the latest posts sent to your email.