简体   繁体   English

使用箭头 python 将字符串转换为日期

[英]Convert string to date using arrow python

I'm trying to convert string to date using arrow module.我正在尝试使用arrow模块将字符串转换为日期。 During the conversion, I received this error: arrow.parser.ParserMatchError: Failed to match '%A %d %B %Y %I:%M:%S %p %Z' when parsing 'Wednesday 06 November 2019 03:05:42 PM CDT'在转换过程中,我收到了这个错误: arrow.parser.ParserMatchError: Failed to match '%A %d %B %Y %I:%M:%S %p %Z' when parsing 'Wednesday 06 November 2019 03:05:42 PM CDT'

The conversion is done using one simple line according to this documentation :根据本文档,使用一条简单的线即可完成转换:

date = arrow.get(date, '%A %d %B %Y %I:%M:%S %p %Z')

I also try to do this with datetime and got another error:我也尝试使用datetime执行此操作,但出现另一个错误:

ValueError: time data 'Wednesday 06 November 2019 03:27:33 PM CDT' does not match format '%A %d %B %Y %I:%M:%S %p %Z'

What am I missing?我错过了什么?

Issue is with timezone, hard-coding timezone here works问题出在时区,硬编码时区在这里有效

import datetime
datetime.datetime.strptime('Wednesday 06 November 2019 03:05:42 PM CDT', '%A %d %B %Y %I:%M:%S %p CDT')

Although you could just hardcode 'CDT' into your code, as @Hamza Rashid auggests in his answer , that will break if the timezone information ever changes to something else, such as 'CST' or perhaps '-0600' .尽管您可以将'CDT'硬编码到您的代码中,正如@Hamza Rashid 在他的回答中所暗示的那样,但如果时区信息更改为其他内容,例如'CST'或可能是'-0600' ,它将中断。

To avoid that potential issue, I'd instead use something like the following, which just ignores everything in the string from the last space character in it onwards:为了避免这个潜在的问题,我会改用类似下面的东西,它只是忽略字符串中从最后一个空格字符开始的所有内容:

import datetime

date = 'Wednesday 06 November 2019 03:05:42 PM CDT'
date = datetime.datetime.strptime(date[:date.rindex(' ')], '%A %d %B %Y %I:%M:%S %p')
print(date)  # -> 2019-11-06 15:05:42

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM