0

Given a TZ-aware datetime, I want to find the datetime of the same time on the previous day in the same timezone (not necessarily same offset).

I came up with the solution below.

tz = pytz.timezone("Europe/Paris")
myDatetime = tz.localize(datetime.datetime(year=2019, month=10, day=27, hour=22))
print(myDatetime) # 2019-10-27 22:00:00+01:00

# separate into date and time
mydate = myDatetime.date()
time = myDatetime.time()
# find previous day
previous_date = mydate - datetime.timedelta(days=1)
print(previous_date) # 2019-10-26

previous_day = tz.localize(datetime.datetime.combine(date=previous_date, time=time))
print(previous_day) # 2019-10-26 22:00:00+02:00

Is there a simpler, better tested, more standard way of doing the same?

Library?

Philipp
  • 4,659
  • 9
  • 48
  • 69

2 Answers2

1

I think this is what you're looking for.

myNewDatetime = tz.localize((myDatetime.replace(tzinfo=None) + datetime.timedelta(days=-1)))

As a heads-up I think you should have made your question a bit more explicit since the issue is really the DST (I had no idea what you meant by offset but figured it out from the date you chose).

soundofsilence
  • 330
  • 2
  • 12
  • Thanks. The DST changes days are the only days which are not 24hrs, thus this is where a difference between subtraction `timedelta(days=1)` and finding the previous day at the same time are different. Unfortunately I think there's some confusion on the web over timezones (which include DTS change rules) vs offset (which is just a fixed difference towards UTC) – Philipp May 04 '20 at 07:56
0

Solution:

tz = pytz.timezone("Europe/Paris")
myDatetime = tz.localize(datetime.datetime(year=2019, month=10, day=27, hour=22))
print(myDatetime) # 2019-10-27 22:00:00+01:00

previous_date = myDatetime - datetime.timedelta(days=1) 
print(previous_date) #2019-10-26 22:00:00+01:00

Hope this is your requirement.

  • Thanks, but this is not what is expected. On that given day, the timezone rules switch the offset from +02:00 to +01:00, which your calculation is not doing – Philipp May 04 '20 at 07:59