1

I have a .csv file with a date format I am unfamiliar with (I think from reading around it's unix).

1607299200000,string,int,float
1607385600000,string,int,float
1606953600000,string,int,float

I have been trying to convert it into '%Y-%m-%d' using Python but keep getting various errors. I am fairly novice with Python but this is what I have so far:

outRow.append(datetime.datetime.strptime(row[0],'%B %d %Y').strftime('%Y-%m-%d'))

Any help would be appreciated.

Ali P
  • 65
  • 8
  • 2
    That's an integer, not a datetime. Most likely a Unix timestamp. You have to convert it to a date first before you can generate a new string with a different format. BTW dates have no format. If you want to work with dates, there's no need to reformat the date – Panagiotis Kanavos Dec 15 '20 at 10:17
  • Does this answer your question? [Converting unix timestamp string to readable date](https://stackoverflow.com/questions/3682748/converting-unix-timestamp-string-to-readable-date) – FObersteiner Dec 15 '20 at 10:53

2 Answers2

2
import datetime
timestamp = datetime.datetime.fromtimestamp(1500000000)
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))

Output:

2017-07-14 08:10:00

DMU
  • 69
  • 8
2

The tricky part here is that you have a unix timestamp with microseconds. AFAIK there's no option to convert unix ts with ms to datetime.

So first you have to drop them (div by 1000), then add them if needed.

ts = row[0]
dt = datetime.utcfromtimestamp(ts//1000).replace(microsecond=ts%1000*1000)

then you can strftime to whichever format you need.

Though if you need to execute this operation for the entire csv, you better look into pandas but that's out of the scope of this question.

Tom Wojcik
  • 5,471
  • 4
  • 32
  • 44