Home > database >  Python datetime timedelta object with timezone
Python datetime timedelta object with timezone

Time:04-08

I have a datetime timedelta object, which I parse from received UTC seconds like this which is an offset from todays midnight:

datetime.timedelta(seconds=seconds)

This is in UTC, but I want to add timezone awareness to it.

So for example now, the seconds=18600 reports 5:10:00 which is correct in UTC.

I want to add a fixed timezone to it, like 'Europe/Budapest', so it will show 6:10:00 or 7:10:00 (based on daytime-saving time).

Is it somehow possible if I don't have a full datetime object, only a timedelta?

Thanks!

CodePudding user response:

Assuming those seconds you get represent the offset since midnight UTC today (or any other particular day), then calculate them exactly as that:

>>> from datetime import datetime, timedelta, timezone
>>> import pytz

>>> midnight = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2022, 4, 8, 0, 0, tzinfo=datetime.timezone.utc)

>>> timestamp = midnight   timedelta(seconds=seconds)
datetime.datetime(2022, 4, 8, 5, 10, tzinfo=datetime.timezone.utc)

>>> local_timestamp = timestamp.astimezone(pytz.timezone('Europe/Budapest'))
datetime.datetime(2022, 4, 8, 7, 10, tzinfo=<DstTzInfo 'Europe/Budapest' CEST 2:00:00 DST>)

CodePudding user response:

Perhaps you would like to offset the timedelta by the UTC offset?

import datetime
import pytz

nowtz = datetime.datetime.now(pytz.timezone("Europe/Budapest"))

seconds = 18600   nowtz.utcoffset().total_seconds()
x = datetime.timedelta(seconds=seconds)
>>> x
7:10:00

Or if you wanted a datetime

# This is a datetime object
>>> nowtz   x
datetime.datetime(2022, 4, 8, 21, 29, 2, 328802, tzinfo=<DstTzInfo 'Europe/Budapest' CEST 2:00:00 DST>)

# This is the above datetime formatted as a string
>>> (nowtz x).strftime("%F %r")
'2022-04-08 09:27:31 PM'
  • Related