-1

This is the list of in unix timestamp

[1626325266384, 1626328880748, 1626332547188, 1626336091854, 1626339628069, 1626343243866, 1626415257315, 1626418895970, 1626422492406, 1626426036647, 1626429722183, 1626433273664, 1626436849458, 1626440458241, 1626444063135,]

Tried almost everything but nothing helped.

Gautam Jha
  • 29
  • 1
  • 6
  • 1
    There are plenty of articles about converting Unix timestamps to datetime objects in Python. What part are you having trouble with? You could try this: `datetimes = [datetime.fromtimestamp(t) for t in timestamps]`, where `timestamps` is your list of timestamps. – Matthias Fripp Aug 09 '21 at 07:26
  • 1
    Can you show what you have tried and how it didn't work? Did you try dividing the values by 1000? – norie Aug 09 '21 at 07:26
  • for i in unixLst: ext = (timestamp.strftime('%Y-%m-%d %H:%M:%S')) – Gautam Jha Aug 09 '21 at 07:29
  • OSError: [Errno 22] Invalid argument Im getting this error when i ran datetimes = [datetime.fromtimestamp(t) for t in timestamps], where timestamps @Matthias Fripp – Gautam Jha Aug 09 '21 at 07:31
  • It looks like you have JavaScript timestamps (milliseconds), not Unix timestamps (seconds). Try dividing by 1000, then using datetime.datetime.fromtimestamp(). – Matthias Fripp Aug 09 '21 at 07:39

1 Answers1

2

Your timestamp contains milliseconds. This is a feasible solution:

import datetime
timestamp_with_ms = 1626325266384
dt = datetime.datetime.fromtimestamp(timestamp_with_ms / 1000)
formatted_time = dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
print(formatted_time)
# 2021-07-15 07:01:06.384

Your specific case requires also a for loop:

my_list = [1626325266384, 1626328880748, 1626332547188, 1626336091854, 1626339628069, 1626343243866, 1626415257315, 1626418895970, 1626422492406, 1626426036647, 1626429722183, 1626433273664, 1626436849458, 1626440458241, 1626444063135]

import datetime
new_list=[]
for i  in my_list:
    timestamp_with_ms = i
    dt = datetime.datetime.fromtimestamp(timestamp_with_ms / 1000)
    formatted_time = dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
    new_list.append(formatted_time)

results:

 ['2021-07-15 07:01:06.384',
 '2021-07-15 08:01:20.748',
 '2021-07-15 09:02:27.188',
 '2021-07-15 10:01:31.854',
 '2021-07-15 11:00:28.069',
 '2021-07-15 12:00:43.866',
 '2021-07-16 08:00:57.315',
 '2021-07-16 09:01:35.970',
 '2021-07-16 10:01:32.406',
 '2021-07-16 11:00:36.647',
 '2021-07-16 12:02:02.183',
 '2021-07-16 13:01:13.664',
 '2021-07-16 14:00:49.458',
 '2021-07-16 15:00:58.241',
 '2021-07-16 16:01:03.135']
BlackMath
  • 1,708
  • 1
  • 11
  • 14