0
from datetime import datetime as dt

time_str = '1606964238000'
ref_time = int(time_str)
ref_time = dt.utcfromtimestamp(ref_time).strftime('%Y-%m-%d %H:%M:%S')

This gives an error:

ValueError                                Traceback (most recent call last)
<ipython-input-10-39d1e0d079a8> in <module>
----> 1 ref_time = dt.utcfromtimestamp(ref_time).strftime('%Y-%m-%d %H:%M:%S')

ValueError: year 52892 is out of range

The same code can parse this unix time correctly:

time_str = '1594553700'

which is '2020-07-12 11:35:00'.

But i am sure the first unixtime is also valid, because it is from docker container machine to generate automatically. How can I parse it into a valid datetime object?

marlon
  • 6,029
  • 8
  • 42
  • 76

2 Answers2

1

Needs to be seconds instead of milliseconds.

from datetime import datetime as dt

time_str = '1606964238000'
ref_time = int(time_str) // 1000
ref_time = dt.utcfromtimestamp(ref_time).strftime('%Y-%m-%d %H:%M:%S')
zrbecker
  • 1,394
  • 1
  • 19
  • 39
  • then how can I accomodate both cases? – marlon Dec 03 '20 at 04:42
  • Technically you cannot simply accommodate both cases without more information. As the other post said, you could check for the length of the number and if it is longer it is "PROBABLY" milliseconds, but seems like you should either have consistency in your code and always use one or the other, or pass along another variable indicating if it is seconds or milliseconds. – zrbecker Dec 08 '20 at 02:04
0

I suspect the problem is that the unix time time_str = '1606964238000' is in milliseconds, while the time_str = '1594553700' is in seconds.

Therefore, you should convert the unix time in milliseconds by dividing by thousand:

from datetime import datetime as dt

time_str = '1606964238000'
ref_time = int(time_str) // 1000 # Use // to ensure we get an integer
ref_time = dt.utcfromtimestamp(ref_time).strftime('%Y-%m-%d %H:%M:%S')
Sebastian
  • 343
  • 1
  • 11
  • Use '/' or '//'? – marlon Dec 03 '20 at 04:43
  • Since we want to ensure we always get an integer "//" is better. I have updated the answer. The difference between '/' and '//' can be read here: https://stackoverflow.com/questions/183853/what-is-the-difference-between-and-when-used-for-division – Sebastian Dec 03 '20 at 05:11
  • Then, how to accomodate both seconds and milliseconds cases in parsing the time? – marlon Dec 03 '20 at 05:12
  • I would say there are two solutions: 1. Check if the length of the string is greater than 10, if so then it's probably in milliseconds. This solution is okay until 11/20/2286 which should be fine. 2. Wrap it in a try catch block and catch the ValueError with the assumption that it is in milliseconds. – Sebastian Dec 03 '20 at 05:22