简体   繁体   中英

Iterate each integer in row in CSV column Python

The csv file has each row in the following format:

527131607.9 Google Maps   

Where there is a total of 2 columns. For this, we are only interested in the first column. I have been using the code:

import datetime
with open("user1_nsdate.csv",'r') as f:
    for row in f:
       for t, val in enumerate(row):
          time = datetime.datetime.fromtimestamp(t+978307200).strftime('%Y-%m-%d %H:%M:%S')

          print(time)

However, the output is wrong as it is not converting correctly:

2001-01-01 00:00:11
2001-01-01 00:00:00
2001-01-01 00:00:01
2001-01-01 00:00:02
2001-01-01 00:00:03
2001-01-01 00:00:04
2001-01-01 00:00:05
2001-01-01 00:00:06

When replacing 't' with an epoch time:

import datetime
with open("user1_nsdate.csv",'r') as f:
    for row in f:
       for t, val in enumerate(row):
          time = datetime.datetime.fromtimestamp(527131607.9 + 978307200).strftime('%Y-%m-%d %H:%M:%S')

          print(time)

output:

2017-09-15 02:26:47
2017-09-15 02:26:47
2017-09-15 02:26:47
2017-09-15 02:26:47
2017-09-15 02:26:47

But i need it to iterate over every row in the first column of the csv file

Change your strftime to .strftime("%d-%m-%y %H:%M:%S")

>>> time = datetime.fromtimestamp(527131607.9+978307200).strftime("%d-%m-%y %H:%M:%S")
>>> print(time)
15-09-17 02:26:47

There's info on all the format codes here:

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

Updated after your comment:

If your file looks like this.

527131607.9
527131127.1
525123123.9
...

You could do something similar to this:

with open('test.csv', 'r') as f:
  for row in f:
    time = datetime.fromtimestamp(float(row)+978307200).strftime("%d-%m-%y %H:%M:%S")
    print(time)

It's a very simple file. I don't think we need to use the built in csv module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM