Parse date and time from string with time zone using Arrow

ぐ巨炮叔叔 提交于 2019-12-05 17:02:46

问题


I have

import arrow
s = '2015/12/1 19:00:00'
tz = 'Asia/Hong_Kong'

How can I parse this with Arrow such that I get an Arrow object with the time zone tz? The following defaults to UTC time.

In [30]: arrow.get(s, 'YYYY/M/D HH:mm:ss')
Out[30]: <Arrow [2015-12-01T19:00:00+00:00]>

I know the .to function but that converts a time zone and but doesn't allow me to change to time zone.


回答1:


Try this:

arrow.get(s, 'YYYY/M/D HH:mm:ss').replace(tzinfo=dateutil.tz.gettz(tz))



回答2:


I'm not qualified yet to add a comment and would just like to share a bit simpler version of the answer with timezone str expression.

s = '2015/12/1 19:00:00'
tz = 'Asia/Hong_Kong'
arrow.get(s, 'YYYY/M/D HH:mm:ss').replace(tzinfo=tz)

or simply local timezone:

arrow.get(s, 'YYYY/M/D HH:mm:ss').replace(tzinfo='local')

or specified ISO-8601 style:

arrow.get(s, 'YYYY/M/D HH:mm:ss').replace(tzinfo='+08:00')



回答3:


Per the current documentation, you can also provide a default timezone for arrow.get(), e.g.:

s = '2015/12/1 19:00:00'
tz = 'Asia/Hong_Kong'
arrow.get(s, tzinfo=tz)

However, as of right now (version 0.12.1) there is a shortcoming where that doesn't work for string-based date parsing. Fortunately, this has been fixed, so the next release of Arrow will integrate this fix.



来源:https://stackoverflow.com/questions/28087218/parse-date-and-time-from-string-with-time-zone-using-arrow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!