'Convert string to date using arrow python
I'm trying to convert string to date using arrow
module.
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'
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:
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?
Solution 1:[1]
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')
Solution 2:[2]
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'
.
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Hamza Rashid |
Solution 2 | martineau |