How to add hours to current time in python
Codemia Knowledge Hub ·
Introduction
Adding hours to the current time in Python uses datetime.now() combined with timedelta(hours=n). The timedelta object represents a duration, and adding it to a datetime produces a new datetime shifted by that amount. This handles day boundaries, month boundaries, and DST transitions correctly when used with timezone-aware datetimes.
Basic Usage with datetime and timedelta
Crossing Day Boundaries
timedelta handles day rollovers automatically:
Timezone-Aware Datetimes
Use zoneinfo (Python 3.9+) for timezone handling:
Using pytz (Pre-Python 3.9)
pytz.normalize() adjusts the UTC offset if the addition crossed a DST boundary.
Using dateutil.relativedelta
relativedelta handles more complex date arithmetic:
Using pandas Timestamp
Formatting the Result
Calculating Hours Between Two Times
Working with time Objects (Not datetime)
Common Pitfalls
- Naive vs aware datetimes:
datetime.now()returns a naive datetime (no timezone). Mixing naive and aware datetimes raisesTypeError. Pick one and stay consistent. Usedatetime.now(tz)for aware datetimes. - DST transitions: Adding 2 hours across a DST boundary may shift the clock by 1 or 3 hours in wall-clock time. Use timezone-aware datetimes and
normalize()(pytz) to handle this correctly. timeobjects cannot add hours:time(14, 0) + timedelta(hours=1)raisesTypeError. Combine with a date first, then extract.time()from the result.- Floating-point hours:
timedelta(hours=1.5)works correctly (1 hour 30 minutes), but avoid accumulating floating-point errors with many additions. Usetimedelta(hours=1, minutes=30)for precision. - UTC vs local time:
datetime.utcnow()returns a naive datetime in UTC. It is not timezone-aware. Usedatetime.now(timezone.utc)instead (Python 3.2+).
Summary
- Use
datetime.now() + timedelta(hours=n)to add hours to the current time timedeltahandles day, month, and year boundaries automatically- Use
zoneinfo.ZoneInfo(Python 3.9+) orpytzfor timezone-aware arithmetic dateutil.relativedeltasupports adding months and years alongside hours- Format results with
strftime()or.isoformat() - Always use timezone-aware datetimes in production to avoid DST and UTC issues
Related reading
- How to add multiple columns to pandas dataframe in one assignment
- How to add pandas data to an existing csv file?
- How to add to the PYTHONPATH in Windows, so it finds my modules/packages?
- How to annotate types of multiple return values?
- How to append a new row to an old CSV file in Python?
- How to append data to TensorFlow tfrecords file
- How to append multiple values to a list in Python
- How to apply a function BigramCollocationFinder to Pandas DataFrame
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.