0

recently I discover problem in my database. 3rd party pass the data as a second and I convert this with python to date and store it to DB. But two different Seconds saved as one date. how can I avoid this? My code:

import datetime

A = datetime.fromtimestamp(1600194600).strftime("%Y-%m-%d %H:%M:%S")
print('A: ' , A)

B = datetime.fromtimestamp(1600198200).strftime("%Y-%m-%d %H:%M:%S")
print('B: ' , B)

And the Result is:

A:  2020-09-15 23:00:00
B:  2020-09-15 23:00:00
a_guest
  • 34,165
  • 12
  • 64
  • 118
M Saberi
  • 49
  • 4
  • I think your import should be `from datetime import datetime`. To which time zone is the machine set to that you use to run this code on? I mean, in which time zone do you wish to display the date? – FObersteiner Apr 09 '21 at 15:20
  • Can not reproduce. Almost surely related to different timezone where code A and code B runs. – wim Apr 09 '21 at 16:02
  • @MrFuppes , I change to `from datetime import datetime` but the problem is exist. But your right. the source data time zone is UTC and my machine is +3:30 – M Saberi Apr 09 '21 at 16:33
  • @wim , A and B have the same Source and they are correct in source application, and both run on my PC – M Saberi Apr 09 '21 at 16:35
  • Hm, did you have a DST change on 2020-9-15 to 2020-9-16? Would be an unusual date but that's the only thing I can think of right now that would explain the duplicate date. – FObersteiner Apr 09 '21 at 16:38
  • No, the DTS change on 2020-09-20. anyway it's ok to me to store data with UTC timezone in DB (exactly like source date). is it possible? – M Saberi Apr 09 '21 at 16:46
  • Sure, added an answer. You might also be interested in having a look at [Display the time in a different time zone](https://stackoverflow.com/q/1398674/10197418). – FObersteiner Apr 09 '21 at 17:01

1 Answers1

0

You can explicitly convert to UTC (aware datetime) by setting the tz argument when calling datetime.fromtimestamp. Ex:

from datetime import datetime, timezone
# Unix time / seconds since the epoch refers to UTC:
A = datetime.fromtimestamp(1600194600, tz=timezone.utc)
B = datetime.fromtimestamp(1600198200, tz=timezone.utc)

print(A.isoformat(' '))
print(B.isoformat(' '))

>>> 2020-09-15 18:30:00+00:00
>>> 2020-09-15 19:30:00+00:00

Now you can convert to a certain time zone, e.g.

from zoneinfo import ZoneInfo # Python 3.9+, for older versions use e.g. backports.zoneinfo
zone = ZoneInfo('Asia/Tehran')

A = A.astimezone(zone)
B = B.astimezone(zone)

print(A.isoformat(' '), str(A.tzinfo))
print(B.isoformat(' '), str(B.tzinfo))

>>> 2020-09-15 23:00:00+04:30 Asia/Tehran
>>> 2020-09-16 00:00:00+04:30 Asia/Tehran
FObersteiner
  • 22,500
  • 8
  • 42
  • 72