如何将纪元时间值转换为本地时间?

How to convert epoch time value to local time?

问题是如何在每一行中传递纪元时间的数值并将其转换为本地时间。

输入文件:log_data.csv

id: 535,    epoch_time: 1611773844,    nsecs: 158737495, state: 2,status: 1
id: 536,    epoch_time: 1611773844,    nsecs: 258731299, state: 2,status: 1
id: 537,    epoch_time: 1611773844,    nsecs: 358585677, state: 4,status: 3
id: 538,    epoch_time: 1611773844,    nsecs: 458462033, state: 2,status: 1

代码片段:

import datetime

def time(data):
 fmt = "%Y-%m-%d %H:%M:%S"
 t = datetime.datetime.fromtimestamp(float(s)/1000.)
 print t.strftime(fmt)

def read_comlumn():
 for line in open("log_cleaning_3_final.log"):
     columns = line.split(',')

您可以使用 csv 模块并从此开始

import csv
import datetime

def convert(data):
  fmt = "%Y-%m-%d %H:%M:%S"
  t = datetime.datetime.fromtimestamp(float(data)/1000.)
  return t.strftime(fmt)

with open('log_cleaning_3_final.log', 'r') as f:
    csv_data = csv.reader(f)
    csv_lines = list(csv_data)

for line in csv_lines:
  line[1] = convert(line[1].split(':')[1].strip())

with open('log_cleaning_3_final.log', 'w') as f:
  writer = csv.writer(f)
  writer.writerows(csv_lines)

你从来没有真正说过你想用转换后的数据做什么——所以我猜到了,下面的代码将它写到一个名为 log_cleaning_3_final.log 的文件中。我还认为你没有提到你使用的 Python 的哪个版本,但我怀疑它是 2.x 并且已经编写了代码以便它在那个版本中工作。

from collections import OrderedDict as odict
import datetime

def time(data):
    t = datetime.datetime.fromtimestamp(float(data)/1000.)
    return t.strftime("%Y-%m-%d %H:%M:%S")

def read_columns(filename):
    columns = []
    with open(inp_filename) as inp:
        for line in inp:
            row = dict([map(str.strip, col.strip().split(':')) for col in line.split(',')])
            row['epoch_time'] = time(row['epoch_time'])  # Convert to local time.
            columns.append(row)
    return columns

def write_columns(cols, filename):
    fieldnames = 'id epoch_time nsecs state status'.split()
    with open(filename, 'w') as outp:
        for row in cols:
            line = odict([(fieldname, row[fieldname]) for fieldname in fieldnames])
            line = ', '.join('{}: {}'.format(k, v) for k, v in line.items())
            outp.write(line + '\n')


cols = read_columns("log_data.csv")
write_columns(cols, "log_cleaning_3_final.log")
print('done')

log_cleaning_3_final.log 输出文件的内容在 运行 以上之后:

id: 535, epoch_time: 1970-01-19 07:42:53, nsecs: 158737495, state: 2, status: 1
id: 536, epoch_time: 1970-01-19 07:42:53, nsecs: 258731299, state: 2, status: 1
id: 537, epoch_time: 1970-01-19 07:42:53, nsecs: 358585677, state: 4, status: 3
id: 538, epoch_time: 1970-01-19 07:42:53, nsecs: 458462033, state: 2, status: 1