📅 Datetime and Time¶
The datetime
module in Python is used for dealing with dates and time.
1. The Datetime Object¶
You can create a datetime
object to represent a specific point in time:
from datetime import datetime
# Create a datetime object for the current date and time
now = datetime.now()
print(now) # e.g., prints: year-month-day hour:minute:second.microsecond
2023-07-04 20:47:49.435519
1.2 The Date Object¶
You can also create a date
object to represent a date without a time:
from datetime import date
# Create a date object for the current date
today = date.today()
print(today) # e.g., prints: year-month-day
2023-07-04
3. The Timedelta Object¶
timedelta
objects represent a duration, or the difference between two dates or times:
from datetime import timedelta
# Create a timedelta of 7 days
week = timedelta(days=7)
# Add 7 days to today's date
next_week = today + week
print(next_week) # e.g., prints: year-month-day
2023-07-11
4. Formatting Dates and Times¶
You can format datetime
objects as strings using the strftime
method, which stands for "string format time". You can also convert strings to datetime
objects using the strptime
method, which stands for "string parse time".
from datetime import datetime
now = datetime.now()
# Convert datetime to string
date_string = now.strftime("%Y-%m-%d %H:%M:%S")
print(date_string) # e.g., prints: 2023-07-02 18:42:05
# Convert string to datetime
date_object = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(date_object) # e.g., prints: year-month-day hour:minute:second
2023-07-04 20:47:49 2023-07-04 20:47:49
5. The time() function¶
The time()
function returns the number of seconds passed since epoch. The epoch is the point where the time starts, and it is platform dependent. For Unix system, the epoch is 1st January 1970.
import time
seconds = time.time()
print(f"Seconds since epoch: {seconds}") # e.g., prints: Seconds since epoch, epoch starts at 1970-01-01 00:00:00
Seconds since epoch: 1688496469.474827
6. The sleep() function¶
The sleep()
function suspends (delays) execution of the current thread for the given number of seconds.
import time
print("This is printed immediately.")
time.sleep(2.5) # waits for 2.5 seconds
print("This is printed after 2.5 seconds.")
This is printed immediately. This is printed after 2.5 seconds.