【问题标题】:Create a datetime from a string representation in a CSV file从 CSV 文件中的字符串表示创建日期时间
【发布时间】:2017-08-30 06:51:42
【问题描述】:

我有一个CSV 文件,其中记录了特定格式的日期时间:

%Y-%m-%d %H:%M:%s %Z

例子:

2017-02-11 14:11:42 PST

我正在尝试将datetime 格式化为更友好的值以供以后使用。

但是,到目前为止,我无法使用我的代码创建 datetime 对象。

这是我的代码:

for r in row:
  purchase_date.append(
    datetime.strptime(row['purchase-date'], "%Y/%m/%d %H:%M:%S %Z")
    )

这是收到的错误:

ValueError: time data '2017-02-11 14:11:42 PST' does not match format %Y/%m/%d %H:%M:%S %Z'

【问题讨论】:

  • 不,它没有。它在日期组件之间有破折号,而不是斜线。
  • @jonrsharpe 好的。如何进一步格式化?
  • 什么?您需要更改格式,使其真正匹配您尝试解析的日期时间。

标签: python csv datetime strptime


【解决方案1】:

在尝试从字符串转换时,时区通常相当不稳定。通常最好自己处理时区字符串。这里有一段代码将时区与时间戳分开,然后分别进行转换。

代码:

import datetime as dt
import pytz

my_timezones = dict(
    PST='US/Pacific',
)

def convert_my_datetime_str(dt_str):
    # split into time and timezone
    timestamp, tz_str = dt_str.rsplit(' ', 1)

    # convert the date string to datetime
    time = dt.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")

    # get a timezone name
    tz = pytz.timezone(my_timezones[tz_str])

    # return a timezone aware datetime
    return tz.localize(time)

测试代码:

print(convert_my_datetime_str('2017-02-11 14:11:42 PST'))

结果;

2017-02-11 14:11:42-08:00

【讨论】:

    【解决方案2】:

    您应该能够更改格式以匹配您的日期字符串。在错误中,您的日期字符串包含破折号而不是斜杠,因此请使格式字符串匹配:

    for r in row:
      purchase_date.append(
        datetime.strptime(row['purchase-date'], "%Y-%m-%d %H:%M:%S %Z")
        )
    

    【讨论】:

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