【问题标题】:How to get time values from list of strings?如何从字符串列表中获取时间值?
【发布时间】:2020-01-31 21:47:42
【问题描述】:

我有一个由时间戳组成的数据集,如下所示:

['2019-12-18T12:06:55.697975Z"', '2019-12-18T12:06:55.707017Z"',...]

我需要一个for 循环,它将遍历所有时间戳并将每个时间戳转换为时间结构。但是我创建的内容不起作用 - 我不确定数据类型以及使用字符串时的索引。 我的尝试如下:

from time import struct_time
for idx in enumerate(tm_str):   #tm_str is a string:['2019-12-18T12:06:55.697975Z"', ...]
    a=idx*30+2  #a should be first digit in year - third position in string - 
    b=idx*30+6  # b should last dgit of year, 30 is period to next year
    tm_year=tm_str[a:b]

月、日、小时等应该以类似的方式完成。

【问题讨论】:

标签: python string datetime


【解决方案1】:

您是否尝试过日期时间库/日期时间对象? https://docs.python.org/3/library/datetime.html

这将创建日期时间对象,您可以使用这些对象进行大量方便的计算。

from datetime import datetime

# your original list:
time_stamp_list = ['2019-12-18T12:06:55.697975Z"', '2019-12-18T12:06:55.707017Z"']

# empty list of datetime objects:
datetime_list = []

# iterate over each time_stamp in the original list:
for time_stamp in time_stamp_list:

    # convert to datetime object using datetime.strptime():
    datetime_object = datetime.strptime(time_stamp, '%Y-%m-%dT%H:%M:%S.%fZ"')

    # append datetime object to datetime object list:
    datetime_list.append(datetime_object)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-27
    • 2016-04-04
    • 2021-07-14
    • 2015-03-11
    • 1970-01-01
    • 2012-05-03
    • 2019-02-21
    • 2011-06-09
    相关资源
    最近更新 更多