Working with dates and times is a common task in programming. Whether you're logging events, scheduling tasks, or analyzing data, understanding how to manipulate dates and times in Python is essential. In this tutorial, we'll explore the datetime module, which provides classes for manipulating dates and times in both simple and complex ways.
The datetime module in Python provides several classes to handle date and time operations:
date: Represents a date (year, month, day).time: Represents a time of day (hour, minute, second, microsecond).datetime: Combines both date and time.timedelta: Represents the difference between two dates or times.We'll also cover how to format and parse dates using strftime() and strptime(), respectively. Additionally, we'll learn how to get the current time and use time.sleep() to pause execution for a specified duration.
date ClassThe date class represents a date (year, month, day). You can create a date object using the date() method:
1from datetime import date23# Create a date object4d = date(2023, 10, 5)5print(d) # Output: 2023-10-05
2023-10-05
time ClassThe time class represents a time of day (hour, minute, second, microsecond). You can create a time object using the time() method:
1from datetime import time23# Create a time object4t = time(14, 30, 45)5print(t) # Output: 14:30:45
14:30:45
datetime ClassThe datetime class combines both date and time. You can create a datetime object using the datetime() method:
1from datetime import datetime23# Create a datetime object4dt = datetime(2023, 10, 5, 14, 30, 45)5print(dt) # Output: 2023-10-05 14:30:45
2023-10-05 14:30:45
timedelta ClassThe timedelta class represents the difference between two dates or times. You can create a timedelta object using the timedelta() method:
1from datetime import timedelta23# Create a timedelta object4td = timedelta(days=5, hours=3)5print(td) # Output: 5 days, 3:00:00
5 days, 3:00:00
strftime()The strftime() method allows you to format date and time objects into strings:
1from datetime import datetime23# Create a datetime object4dt = datetime(2023, 10, 5, 14, 30, 45)56# Format the datetime object7formatted_date = dt.strftime("%Y-%m-%d %H:%M:%S")8print(formatted_date) # Output: 2023-10-05 14:30:45
2023-10-05 14:30:45
strptime()The strptime() method allows you to parse strings into date and time objects:
1from datetime import datetime23# Parse a string into a datetime object4date_string = "2023-10-05 14:30:45"5dt = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")6print(dt) # Output: 2023-10-05 14:30:45
2023-10-05 14:30:45
You can get the current date and time using the now() method of the datetime class:
1from datetime import datetime23# Get the current datetime4now = datetime.now()5print(now) # Output: e.g., 2023-10-05 14:30:45.123456
e.g., 2023-10-05 14:30:45.123456
time.sleep()The time.sleep() function pauses the execution of a program for a specified number of seconds:
1import time23print("Starting...")4time.sleep(2) # Pause for 2 seconds5print("2 seconds have passed.")
Starting... 2 seconds have passed.
Let's create a simple program that logs the current date and time every second for 10 seconds:
1import time2from datetime import datetime34print("Logging start...")5for _ in range(10):6now = datetime.now()7print(f"{now} - Logging")8time.sleep(1)9print("Logging end.")
Logging start... 2023-10-05 14:30:45.123456 - Logging 2023-10-05 14:30:46.123456 - Logging 2023-10-05 14:30:47.123456 - Logging 2023-10-05 14:30:48.123456 - Logging 2023-10-05 14:30:49.123456 - Logging 2023-10-05 14:30:50.123456 - Logging 2023-10-05 14:30:51.123456 - Logging 2023-10-05 14:30:52.123456 - Logging 2023-10-05 14:30:53.123456 - Logging 2023-10-05 14:30:54.123456 - Logging Logging end.
| Concept | Description |
|---|---|
date | Represents a date (year, month, day). |
time | Represents a time of day (hour, minute, second, microsecond). |
datetime | Combines both date and time. |
timedelta | Represents the difference between two dates or times. |
strftime() | Formats date and time objects into strings. |
strptime() | Parses strings into date and time objects. |
now() | Gets the current date and time. |
time.sleep() | Pauses the execution of a program for a specified number of seconds. |
In the next tutorial, we'll explore Python Regular Expressions, which are powerful tools for working with text data. Regular expressions allow you to search, match, and manipulate strings in complex ways. Stay tuned!