In Python, date and time refer to the ability to work with dates, times, and their combinations using various built-in libraries and modules. Python provides several tools for handling dates and times, which makes it easier to perform operations like formatting, arithmetic, and comparisons.
1. datetime
module:
The primary module used for working with dates and times in Python is the datetime
module. This module includes several classes such as date
, time
, datetime
, and timedelta
.
datetime.date
: Represents the date (year, month, day).datetime.time
: Represents time (hour, minute, second, microsecond).datetime.datetime
: Represents both date and time.datetime.timedelta
: Represents the difference between two dates or times (useful for date/time arithmetic).
2. Basic operations:
Here are some common operations using the datetime
module:
- Getting the current date and time:
import datetime current_datetime = datetime.datetime.now() print(current_datetime)
- Creating a specific date and time:
specific_date = datetime.date(2025, 1, 16) specific_time = datetime.time(14, 30, 45) specific_datetime = datetime.datetime(2025, 1, 16, 14, 30, 45) print(specific_date) print(specific_time) print(specific_datetime)
- Formatting date and time:
current_datetime = datetime.datetime.now() formatted = current_datetime.strftime("%Y-%m-%d %H:%M:%S") print(formatted)
- Parsing a string to a date or time:
date_string = "2025-01-16" parsed_date = datetime.datetime.strptime(date_string, "%Y-%m-%d") print(parsed_date)
- Date arithmetic (using
timedelta
):today = datetime.date.today() tomorrow = today + datetime.timedelta(days=1) print(f"Today: {today}, Tomorrow: {tomorrow}")
3. Timezone support:
Python also supports time zone-aware dates and times using the pytz
library or the built-in timezone
class in datetime
.
4. Epoch Time:
In Python, the epoch time (also known as UNIX timestamp) is the number of seconds that have passed since January 1, 1970, at 00:00:00 UTC.
- Getting the current time in epoch:
epoch_time = datetime.datetime.now().timestamp() print(epoch_time)
Summary:
The datetime
module allows you to create, manipulate, and format dates and times, perform arithmetic on them, and even work with time zones and epochs. It is an essential tool for any Python developer working with time-related data.