Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse date and time from string with time zone using Arrow

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.

like image 351
mchangun Avatar asked Jan 22 '15 11:01

mchangun


3 Answers

Try this:

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

If you are also using dateutil, this works as well:

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

So does this:

arrow.get(s, 'YYYY/M/D HH:mm:ss').replace(tzinfo=dateutil.tz.gettz(tz))
like image 81
Matt Johnson-Pint Avatar answered Nov 02 '22 18:11

Matt Johnson-Pint


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')
like image 38
Quake Lai Avatar answered Nov 02 '22 19:11

Quake Lai


This is working for me as of 0.10.0:

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

arrow.get(s, 'YYYY/M/D HH:mm:ss', tzinfo=tz)
# <Arrow [2015-12-01T19:00:00+08:00]>

However, arrow.get('2018-01-29 14:46', tzinfo='US/Central') (i.e. without the format string) ignores the tzinfo parameter.

like image 1
Raijinili Avatar answered Nov 02 '22 17:11

Raijinili