Python Date and Time
1. Getting the Current Date and Time:
Definition:
In Python, the datetime
module is used to work with dates and times.
Example:
from datetime import datetime
# Get current date and time
now = datetime.now()
print(now) # Output: Current date and time, e.g., 2024-11-24 14:30:15.123456
Output:
2024-11-24 14:30:15.123456
2. Formatting Date and Time:
Definition:
You can format the date and time in various ways using the strftime()
method.
Syntax:
formatted_date = datetime.now().strftime("Format_String")
Example:
from datetime import datetime
# Get current date and time in specific format
formatted_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date) # Output: 2024-11-24 14:30:15
Output:
2024-11-24 14:30:15
3. Parsing a Date from a String:
Definition:
To convert a string into a date object, the strptime()
method is used.
Syntax:
date_object = datetime.strptime(date_string, "Format_String")
Example:
from datetime import datetime
# Convert a string to a date object
date_string = "2024-11-24 14:30:15"
date_object = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(date_object) # Output: 2024-11-24 14:30:15
Output:
2024-11-24 14:30:15
4. Getting Today's Date
Definition:
The date()
method is used to get only the date part (without the time).
Syntax:
today = datetime.today().date()
Example:
from datetime import datetime
# Get today's date
today = datetime.today().date()
print(today) # Output: 2024-11-24
Output:
2024-11-24
5. Time Difference (Timedelta) :
Definition:
You can calculate the difference between two dates using timedelta
.
Syntax:
from datetime import timedelta
date_difference = date1 - date2
Example:
from datetime import datetime, timedelta
# Current date and time
now = datetime.now()
# Subtract 10 days from the current date
ten_days_ago = now - timedelta(days=10)
print(ten_days_ago) # Output: Date 10 days ago
Output:
2024-11-14 14:30:15.123456
6. Adding or Subtracting Days, Months, or Years :
Definition:
You can add or subtract days, months, or years using timedelta
or a custom function.
Example:
from datetime import datetime, timedelta
# Add 30 days to the current date
current_date = datetime.now()
future_date = current_date + timedelta(days=30)
Output:
2024-12-24 14:30:15.123456
0 Comments