【问题标题】:Change format from ISo8601 timestamp to datetime将格式从 ISO8601 时间戳更改为日期时间
【发布时间】:2022-09-28 20:59:39
【问题描述】:

我有一列格式为:1.727783203125, 2022-09-15T18:18:12.987 如何将 ISO 8601 格式更改为整列的日期时间?

谢谢!

  • 一个……专栏?在哪里?您是否正在阅读具有逗号分隔值的文件..?你能显示你当前的代码吗?
  • 我什至还没有代码。我只有一个带有 ISO8601 时间戳的 csv 文件。但是 Python 无法使用 ISO8601 绘制任何内容,因此我必须将它们转换为 Python 可以使用的日期时间。

标签: python csv iso8601


【解决方案1】:

使用内置的csv 模块,

import io
import csv
import datetime

# This stands in for `f = open("something.csv")` to make
# this example self-contained.

f = io.StringIO("""
1.727783203125,2022-09-15T18:18:12.987
1.927783203125,2022-09-15T19:18:12
""".strip())

# Iterate over CSV rows, parse the first column as float and the second as a datetime.
data = [(float(x), datetime.datetime.fromisoformat(y)) for x, y in csv.reader(f)]

print(data)

打印出来

[
  (1.727783203125, datetime.datetime(2022, 9, 15, 18, 18, 12, 987000)), 
  (1.927783203125, datetime.datetime(2022, 9, 15, 19, 18, 12, 0))
]

你也可以使用 Pandas,但如果这真的是你所需要的,那就有点矫枉过正了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多