Working with Dates and Times
Dates and Times:
1. Importing the datetime Module:
- Import the datetime module to access date and time classes.
2. Date and Time Objects:
- datetime.date: Represents a date (year, month, day).
- datetime.time: Represents a time (hour, minute, second, microsecond).
3. Creating Date and Time Objects:
- Instantiate date and time objects with relevant values.
- datetime.datetime: Represents both date and time together.
Working with datetime Objects:
1. Current Date and Time:
- Get the current date and time using datetime.now().
2. Accessing Components:
- Access individual components of a datetime object (year, month, day, hour, etc.).
- Use attributes like .year, .month, .day, .hour, .minute, .second.
3. Formatting and Display:
- Convert datetime objects to formatted strings using .strftime().
- Specify formatting codes for each component (e.g., %Y for year, %m for month).
Timezones and Timedeltas:
1. Timezones:
- Use the pytz library to work with timezone.
- Convert between different timezones using datetime.astimezone().
2. Timedeltas:
- Represent the difference between two dates or times using datetime.timedelta.
- Perform arithmetic operations with timedelta objects.
Parsing and Formatting:
1. Parsing Strings into datetime Objects:
- Use datetime.strptime() to convert strings to datetime objects.
- Specify the input format string to match the input format.
2. Formatting datetime Objects to Strings:
- Use .strftime() to format datetime objects to strings.
- Choose formatting codes to represent different components.
Example:
Here's a simple example demonstrating the use of the datetime module:
import datetime
# Current date and time current_datetime = datetime.datetime.now() print("Current Date and Time:", current_datetime)
# Accessing components print("Year:", current_datetime.year) print("Month:", current_datetime.month) print("Day:", current_datetime.day) print("Hour:", current_datetime.hour) print("Minute:", current_datetime.minute) print("Second:", current_datetime.second)
# Formatting datetime to string formatted_date = current_datetime.strftime("%Y-%m-%d") print("Formatted Date:", formatted_date)
|