【问题标题】:Python - Read only the time from a .csv Datetime string column, then convert time to UTCPython - 仅读取 .csv 日期时间字符串列中的时间,然后将时间转换为 UTC
【发布时间】:2016-07-10 03:55:52
【问题描述】:

简而言之,我有一个程序可以打开一个 .csv 文件,读取 .csv 文件,然后将包含日期时间字符串数据的列合并到一个新的 .csv 文件中。但是,在程序将列合并到新文件之前,我首先需要从 datetime 字符串中仅读取时间,然后将时间转换为 UTC,然后将其合并到新的 .csv 文件中。

由于数据存储在 .csv 文件中,当检索到它时,它会以字符串形式出现:

"1/28/2016  3:52:49 PM"

如何仅读取 3:52:49 并将其设为 35249,然后将其转换为 UTC 时间,然后将时间作为新列存储在新的 .csv 文件中?

如果您需要我的代码:

import os
import csv
import datetime as dt
from os import listdir
from os.path import join 
import matplotlib.pyplot as plt

#get the list of files in mypath and store in a list

mypath = 'C:/Users/Alan Cedeno/Desktop/Test_Folder/'
onlycsv = [f for f in listdir(mypath) if '.csv' in f]

#print out all the files with it's corresponding index

for i in range(len(onlycsv)):
    print(i,onlycsv[i])

#prompt the user to select the files

option = input('please select file1 by number: ')
option2 = input('please select file2 by number: ')

#build out the full paths of the files and open them

fullpath1 = join(mypath, onlycsv[option])
fullpath2 = join(mypath, onlycsv[option2])

#create third new.csv file

root, ext = os.path.splitext(fullpath2)
output = root + '-new.csv'

with open(fullpath1) as r1, open(fullpath2) as r2, open(output, 'a') as w:
    writer = csv.writer(w)
    merge_from = csv.reader(r1)
    merge_to = csv.reader(r2)
# skip 3 lines of headers
for _ in range(3):
    next(merge_from)
for _ in range(1):
    next(merge_to)
for merge_from_row, merge_to_row in zip(merge_from, merge_to):
    # insert from col 0 as to col 0
    merge_to_row.insert(1, merge_from_row[2])
    # replace from col 1 with to col 3
    #merge_to_row[0] = merge_from_row[2]
    # delete merge_to rows 5,6,7 completely
    #del merge_to_row[5:8]
    writer.writerow(merge_to_row)

【问题讨论】:

标签: python csv datetime


【解决方案1】:

日期时间库就是您要查找的内容:https://docs.python.org/2/library/datetime.html

>>> from datetime import datetime
>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
>>> dt
datetime.datetime(2006, 11, 21, 16, 30)

使用dt.strftime(format) 将日期转换为您需要的格式

-- 下面是您问题的解决方案,如果您需要进行其他日期操作,上面应该希望将您链接到一些资源

How do I convert local time to UTC in Python?

>>> def local_to_utc(t):
...     secs = time.mktime(t)
...     return time.gmtime(secs)
>>> a = local_to_utc(dt.timetuple())

我们获取结果,并将其传回,然后以所需的格式转储出来

>>> datetime.fromtimestamp(time.mktime(a)).strftime("%H:%m:%S")

【讨论】:

  • python 3 显然可以更好地处理时区:\
  • 但是一旦我获得了我需要的格式,我该如何采用该格式并将其作为新列存储在 .csv 文件中?
  • 1- 使用%Y 而不是%y -- OP 使用 4 位数年份 2- 过去本地 utc 偏移量可能不同,本地时间可能不明确,因此 mktime()可能会失败。 If the timestamps are consecutive in the csv file then you could resolve the ambiguity in some cases 3- (至少)调用 fromtimestamp(mktime(dt.timetuple())) 毫无意义——如果它有效的话;它相当于dt,即直接使用dt.strftime("%H:%M:%S")。 4-顺便说一句,使用%M而不是%m来打印分钟
猜你喜欢
  • 2014-02-22
  • 1970-01-01
  • 2011-06-13
  • 1970-01-01
  • 2012-03-15
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 2014-11-18
相关资源
最近更新 更多