Practical Examples of Time Manipulation

Laptop displaying code with reflection, perfect for tech and programming themes.

Adding and Subtracting Time

You can manipulate time using `timedelta` objects.

Adding 10 days to the current date

from datetime import datetime, timedelta

now = datetime.now()

future_date = now + timedelta(days=10)

print(“Date after 10 days:”, future_date)

Subtracting 5 hours from the current time

past_time = now – timedelta(hours=5)

print(“Time 5 hours ago:”, past_time)

Converting Between Time Zones

Handling time zones accurately requires the `pytz` library.

Converting UTC to a different time zone

from datetime import datetime

import pytz

utc_time = datetime.utcnow().replace(tzinfo=pytz.UTC)

local_time = utc_time.astimezone(pytz.timezone(‘US/Pacific’))

print(“Pacific Time:”, local_time)

Formatting Dates and Times

Use the `strftime` method for formatting.

Formatting the current date and time

formatted_date = now.strftime(“%Y-%m-%d %H:%M:%S”)

print(“Formatted date and time:”, formatted_date)

Parsing Strings to Datetime

The `strptime` method parses a string into a `datetime` object.

Parsing a date string

date_string = “2023-10-15 08:30:00”

parsed_date = datetime.strptime(date_string, “%Y-%m-%d %H:%M:%S”)

print(“Parsed date:”, parsed_date)

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top