Pyhton Dates
Python has a built-in module called datetime
that provides classes and functions to work with dates and times. Here’s an overview of how you can work with dates in Python:
- Import the
datetime
module:python
import datetime
Get the current date and time:
python
current_datetime = datetime.datetime.now()
print(current_datetime)
Create a specific date and time:
python
specific_datetime = datetime.datetime(2022, 4, 15, 12, 30, 0)
print(specific_datetime)
Extract specific components from a datetime object:
python
year = specific_datetime.year
month = specific_datetime.month
day = specific_datetime.day
hour = specific_datetime.hour
minute = specific_datetime.minute
second = specific_datetime.second
Format a datetime object as a string:
python
formatted_datetime = specific_datetime.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_datetime)
Parse a string into a datetime object:
python
parsed_datetime = datetime.datetime.strptime("2022-04-15 12:30:00", "%Y-%m-%d %H:%M:%S")
print(parsed_datetime)
Perform arithmetic operations with dates:
python
future_datetime = specific_datetime + datetime.timedelta(days=30)
past_datetime = specific_datetime - datetime.timedelta(weeks=2)
Compare dates:
python
is_future = future_datetime > specific_datetime
is_past = past_datetime < specific_datetime
Get the difference between two dates:
python
time_difference = future_datetime - specific_datetime print(time_difference.days) # number of days between the two dates
These are just some basic operations with dates in Python. The datetime
module provides many more functionalities for date and time manipulation.