The datetime
module in Python is a powerful tool for handling dates and times. In this blog post, I will cover essential datetime
functions with simple Python code snippets.
Get the Current Date and Time
To get the current date and time, use the datetime.now()
method.
from datetime import datetime
now = datetime.now()
print("Current Date and Time:", now)
This returns a timestamp with the current date and time.
Format Date and Time
You can format the output of datetime
using strftime()
function.
from datetime import datetime
now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print("Current Date and Time:", formatted_date)
- %Y – Year
- %m – Month
- %d – Day
- %H – Houra
- %M – Minutes
- %S – Seconds
Add or Subtract from a Datetime
If you want to add or subtract days, hours, minutes, or seconds from a datetime, you can use the timedelta()
function.
from datetime import datetime
from datetime import timedelta
now = datetime.now()
future_date = now + timedelta(days=10, hours=23, minutes=50, seconds=45)
print("Future Date (after 10 days):", future_date)
past_date = now - timedelta(days=10)
print("Past Date (10 days ago):", past_date)
Convert Datetime to Different Timezones
Using the pytz
module, you can convert between time zones.
from datetime import datetime, UTC
import pytz
# current date and time in UTC
now = datetime.now()
utc_now = datetime.now(UTC)
print("UTC Time:", utc_now)
# Convert to NY timezone
ny_tz = pytz.timezone("America/New_York")
ny_time = utc_now.replace(tzinfo=pytz.utc).astimezone(ny_tz)
print("NY Time:", ny_time)
If you want to find the list of all timezones, you can use the following code:
import pytz
timezones = pytz.all_timezones
for tz in timezones:
print(tz)