Explain Codes LogoExplain Codes Logo

How to add hours to current time in python

python
datetime-manipulation
timezones
dateutil
Alex KataevbyAlex Kataev·Jan 12, 2025
TLDR

To add hours to the present time in Python, the datetime.now() function and the timedelta class will serve you well:

from datetime import datetime, timedelta # Current time is fleeing! Let's add 3 hours! new_time = datetime.now() + timedelta(hours=3) print(new_time)

This straightforward method calculates the new time by appending 3 hours to the current moment.

Diving deeper: Enhancing your time manipulation skills

While the quick answer offers a rapid solution, gaining a deeper knowledge of datetime manipulation would make your code more resilient. Here's how you can maximise the utility of Python's datetime module.

Managing multiple timezones

Working across various time zones requires the zoneinfo module. Don't forget to import it with datetime and timedelta to make your hours aware of timezones:

from datetime import datetime, timedelta, timezone from zoneinfo import ZoneInfo # Gimme New York time baby! current_time = datetime.now(ZoneInfo("America/New_York")) # Adding 3 hours, just a click of a finger! new_time = current_time + timedelta(hours=3)

Formatting time your way

At times, a particular time format is required. With Python's strftime method, you can pick from a smorgasbord of format codes to serve your needs:

# Let's make it pretty! formatted_time = new_time.strftime('%H:%M:%S') print("New time:", formatted_time)

Creating reusable functions

To reduce redundancy, it's a good idea to encase the logic inside a function. This helps make your code cleaner and more reusable:

# An hour-adding machine! def add_hours_to_current_time(hours): return datetime.now() + timedelta(hours=hours) # Let's test this beauty print(add_hours_to_current_time(3))

Please consider edge cases like daylight saving time adjustments and transitions to UTC using timezone.utc.

Broadening your scope: Advanced techniques

To take your time manipulation skills up several notches, consider apperceiving advanced techniques that cater to diverse complicated scenarios.

Dealing with Unix timestamps

Especially when dealing with databases or APIs, you might have to work with Unix timestamps. Here's a way to perform the conversion:

# Unix timestamp, you're next! timestamp = int(new_time.timestamp()) print("Timestamp:", timestamp)

Time format juggling

In scenarios where you need to swap between different time formats, strftime (conversion from datetime to string) and strptime (conversion from string to datetime) are incredibly handy:

# Let's turn the tables around! time_str = '15:30:00' time_obj = datetime.strptime(time_str, '%H:%M:%S') # 3 hours for a time-travel journey! new_time_obj = time_obj + timedelta(hours=3)

When using strptime, ensure the format string and input string structure align perfectly.

Creative date-time computations with dateutil

For more complex operations, the dateutil module offers functionalities to handle recurrence or relative deltas:

from dateutil.relativedelta import relativedelta # A little more flexibility, shall we? new_time = current_time + relativedelta(hours=+3)

With relativedelta, you have the capacity to handle more nuanced adjustments, perhaps the end of the month or dealing with weeks and years.