[英]parsing dates in the form of strings using arrow date manipulating python library
I am looking to convert the string "september 20 2010"
to a python datetime.date
object using arrow
. 我希望使用
arrow
将字符串"september 20 2010"
转换为python datetime.date
对象。
I have written functions to replace portions of the text and ended up with 9/20/2016 but I want YYYY-MM-DD format and can't seem to get arrow
to recognise my string and convert it to a python datetime.date
object (without any time). 我已经编写了函数来替换部分文本并最终得到9/20/2016但我想要YYYY-MM-DD格式并且似乎无法获得
arrow
来识别我的字符串并将其转换为python datetime.date
对象(没有任何时间)。
What has worked and what hasn't. 什么有效,什么没有。
arrow.get('september 20 2010', '%B %d %Y')
arrow.get('2010年9月20日','%B%d%Y')
this doesn't work for me I get an error: ParserError: Failed to match '%B %(?P<d>[1-7]) %Y'
when parsing the string "september 20 2010"
这对我不起作用我得到一个错误:
ParserError: Failed to match '%B %(?P<d>[1-7]) %Y'
解析字符串"september 20 2010"
时ParserError: Failed to match '%B %(?P<d>[1-7]) %Y'
However when I manipulate the string and then use arrow.Arrow(y,m,d).date()
, the result is a datetime.date(2016, 9, 20)
object. 但是当我操作字符串然后使用
arrow.Arrow(y,m,d).date()
,结果是datetime.date(2016, 9, 20)
arrow.Arrow(y,m,d).date()
datetime.date(2016, 9, 20)
对象。
I just can't convert it to any other format using .format('dddd-DD-MMMM-YYYY')
which would return Monday 20 Septemb 2010 . 我无法使用
.format('dddd-DD-MMMM-YYYY')
将其转换为任何其他格式,该格式将于2010年9月20日星期一返回。
Using arrow
, you have to match the exact syntax of your string, here is the list of the associated token . 使用
arrow
,您必须匹配字符串的确切语法,这是相关标记的列表。
arrow.get('September 20 2010', 'MMMM D YYYY')
Note : In this very case, there is only one D
because it cover the number with one or two digits 1, 2, 3... 29, 30 while DD
cover the number with two digits only 01, 02, 03 ... 29, 30 注意 :在这种情况下,只有一个
D
因为它用一个或两个数字1,2,3 ... 29,30覆盖数字,而DD
覆盖数字只有两个数字01,02,03 ...... 29,30
Once you get your arrow object, you can display it however you like using format() : 获得箭头对象后,您可以使用format()显示它:
ar = arrow.get('September 20 2010', 'MMMM D YYYY')
print(ar.format('YYYY-MM-DD')) # 2010-09-20
EDIT 编辑
To answer your comment, ar
is an Arrow object and you can check every method it contained with dir
要回答你的评论,
ar
是一个Arrow对象,你可以用dir
检查它包含的每个方法
Arrow
have a method date()
which returns a datetime.date
object. Arrow
有一个方法date()
,它返回一个datetime.date
对象。
Now, if you want to use pandas
, that's easy: 现在,如果你想使用
pandas
,这很容易:
import array
import pandas as pd
ar = arrow.get('September 20 2010', 'MMMM D YYYY')
df = pd.to_datetime(ar.date())
print(df) # 2010-09-20 00:00:00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.