2

I have a bunch of time objects stored in a database but they are all naive objects. The time they store is in 'JST' or 'Asia/Tokyo' tz. I tried using

naive_time.replace(tzinfo = pytz.timezone('Asia/Tokyo'))

but this sets it to LMT+09:19:00 which is incorrect, it should be LMT+09:00:00. Any suggestions to do it rightly.

Edit: The database returns the time as datatime.time object with tzinfo=None like datetime.time(1, 0). I assigned this to t and tried

t.replace(tzinfo = pytz.timezone('Asia/Tokyo'))

which gave

datetime.time(1, 0, tzinfo=<DstTzInfo 'Asia/Tokyo' LMT+9:19:00 STD>)

but 'Asia/Tokyo' or JST is 9 hours ahead of LMT not 9 hours 19 minutes.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
TheWhiteFang
  • 745
  • 5
  • 16
  • 1
    Welcome to SO, could you update your post to make your issue reproducible. At the moment we can only speculate on what happens. Please read [mcve] to get more insights about how to make your post meets SO Standards. – jlandercy Dec 24 '19 at 09:56
  • Does this answer your question? [Why does datetime give different timezone formats for the same timezone?](https://stackoverflow.com/questions/52217506/why-does-datetime-give-different-timezone-formats-for-the-same-timezone) – jlandercy Dec 24 '19 at 10:01
  • no it doesn't. I saw that answer earlier but it didn't help – TheWhiteFang Dec 24 '19 at 10:09
  • the naive time object that i have stores value in this format `datetime.time(1, 0)` if i do `.replace(tzinfo = pytz.timezone('Asia/Tokyo'))` then it returns `datetime.time(1, 0, tzinfo=)` which is incorrect. the expected result should be `datetime.time(1, 0, tzinfo=)` – TheWhiteFang Dec 24 '19 at 10:14
  • Please could you post the complete code of your [mcve] (including imports and a datetime or time object as it is stored in your database). – jlandercy Dec 24 '19 at 10:23

1 Answers1

4

You will have to add a date so you can localize it. Otherwise the determination of DST is ambiguous: countries can choose if and when to use DST which lead to a lot of changes over time. See e.g. timeanddate.com for JST. If you want to dig deep, check out the IANA database.

Example:

import datetime
import pytz

naive_time = datetime.time(1, 0)

date = datetime.date(2019, 12, 24)
comb_time = datetime.datetime.combine(date, naive_time)

tz = pytz.timezone('Asia/Tokyo')
loc_time = tz.localize(comb_time)

# loc_time
# datetime.datetime(2019, 12, 24, 1, 0, tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>)

You can find more info in Martijn Pieter's answer here why you should not use the replace method to set the timezone for naive datetime objects.

A general note which must not be missing in this context: always work with UTC internally if possible in any way - only determine local times for output to be read by humans.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72