0

I don't have experience in working with timestamps. I started analyzing new data frames containing a column of timestamp such as: time= 1599091199986769056. I would like to transform a column of timestamps to date and time. so I tried the following for one row:

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

But I get the following error:

----> 1 print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

OSError: [Errno 22] Invalid argument

Can anyone tell me what I'm doing wrong and how can I turn a column from timestamp to date time ?

the phoenix
  • 641
  • 7
  • 15
  • 2
    Do you have any indication what format that timestamp is in and/or roughly what value you expect from it? It's most definitely not a standard UNIX timestamp *in seconds*, nor milliseconds. You have to divide by at least 100000000 to get a usable UNIX timestamp. – deceze Oct 14 '20 at 08:55
  • By looking at the timestamp value, it seems that there is a format issue. Maximum allowed value is 32536799999 - https://stackoverflow.com/q/46133223/13640294 – kartik sharma Oct 14 '20 at 09:00
  • 2
    seems to be nanoseconds; so use `ts/1e9` as input to `fromtimestamp`. and btw. try [not to use utcfromtimestamp](https://blog.ganssle.io/articles/2019/11/utcnow.html) to avoid confusion. – FObersteiner Oct 14 '20 at 09:01
  • 1
    since you mention *column of timestamps* - are you using `pandas`? if so, you can easily convert a column holding nanosecond timestamps to datetime using `pd.to_datetime`. See e.g. [here](https://stackoverflow.com/questions/40038169/pandas-timestamp-to-datetime), just omit the `unit` keyword since nanoseconds are the default. – FObersteiner Oct 14 '20 at 09:05

1 Answers1

1

You can use the to_datetime function:

import pandas as pd

ts = int("1599091199986769056")

df = pd.DataFrame([ts], columns=['Timestamp'])
df['Timestamp'] = pd.to_datetime(df['Timestamp'])
print(df)

Output:

                      Timestamp
0 2020-09-02 23:59:59.986769056
PythonSherpa
  • 2,560
  • 3
  • 19
  • 40