1

I have a string 1615070997520. This is a Unix timestamp, but this is for millisecond. When I convert this to date with converter, It gives me correct date (Saturday, March 6, 2021 10:49:57.520 PM GMT).

But with this code:

from datetime import datetime
ts = int("1615070997520")
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

It gives me an error which is ValueError: year 53149 is out of range.

Is there any way to convert it into correct date like yyyy-mm-dd hh:mm:ss.ms using Python?

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
Superjay
  • 447
  • 1
  • 7
  • 25
  • 2
    Divide `ts` by 1000 first: `.utcfromtimestamp(ts/1000)` – Selcuk Mar 07 '21 at 05:48
  • Exact dupe of [Converting unix timestamp string to readable date](https://stackoverflow.com/questions/3682748/converting-unix-timestamp-string-to-readable-date) – FObersteiner Mar 07 '21 at 10:38
  • also note: `utcfromtimestamp` can be misleading, https://stackoverflow.com/a/65076703/10197418 – FObersteiner Mar 07 '21 at 10:40
  • @MrFuppes No. I am talking about a millisecond Unix time which is the length of 13, not 10 – Superjay Mar 08 '21 at 08:33
  • @MrFuppes Then any alternatives you recommend? `time.time()` works finely? – Superjay Mar 08 '21 at 08:37
  • Why do you think it makes a difference if you have seconds or milliseconds (or whatever) since the epoch - it's still the same *principle*, no? Then, the number of digits depends on how many units of time you're after the epoch. This is not some independent property. – FObersteiner Mar 08 '21 at 09:18
  • `time.time()` *returns* seconds since the epoch, that's the other way 'round. If you want to work with datetime objects which you obtain from such timestamps, I recommend working with [aware datetime](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects) (which is *not* what `utcfromtimestamp` returns). See also [Paul's blog](https://blog.ganssle.io/articles/2019/11/utcnow.html) for some background info. – FObersteiner Mar 08 '21 at 09:21

1 Answers1

2

Try this one

ts = int("1615070997520")/1000
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
Sivaram Rasathurai
  • 5,533
  • 3
  • 22
  • 45