Python Arrow Not Formatting Date Properly

1k Views Asked by At

I am using the Python Arrow package for formatting a date that I've got.

My input is:

datetime=2017-10-01T00:10:00Z and timezone=US/Pacific

My expected output is:

Sun 10/01 @ 6:10pm

I've tried a host of different date time conversions but I always end up with Sun 10/01 @ 12:10AM which is not time zone dependent.

If I try and say:

x = arrow.Arrow.strptime('2017-10-01T00:10:00Z', 
                         '%Y-%m-%dT%H:%M:%SZ',
                         tzinfo=tz.gettz('US/Pacific'))

x is equal to:

<Arrow [2017-10-01T00:10:00-07:00]>

I then say:

x.strftime('%a %m/%d @ %I:%M%p')

and it outputs

Sun 10/01 @ 12:10AM

The Arrow object knows about the timezone as evidenced by the -7:00 but does not format the date accordingly.

Any ideas?

1

There are 1 best solutions below

0
On

I think that there are a couple of misunderstandings in this question.

Convert to a timezone

I can see no way that the timestamp,

2017-10-01T00:10:00Z and timezone=US/Pacific

Can become,

Sun 10/01 @ 6:10pm

There are several problems here.

  1. The Z at the end of the timestamp is a timezone and means Zulu aka GMT, so the timestamp already has a timezone.
  2. If we ignore problem #1, then for that timestamp 10 minutes after midnight (minus the Z) to become 6:10 pm the same day would require a timezone that was +18. This timezone does not exist.
  3. US/Pacific is -7/-8 depending on the time of the year. If we accept the Z as the timezone and want to convert to US/Pacific, then the time should be 9/31 at 5:10pm

What does -7:00 mean?

So I am going to guess that what you intend is that the timestamp is in fact Zulu, and you want to display that timestamp as US/Pacific. If this is true than you need to do:

from dateutil import tz
import arrow
x = arrow.Arrow.strptime(
    '2017-10-01T00:10:00Z',
    '%Y-%m-%dT%H:%M:%SZ').to(tz.gettz('US/Pacific'))

print(x)
print(x.strftime('%a %m/%d @ %I:%M%p'))

This results in:

2017-09-30T17:10:00-07:00
Sat 09/30 @ 05:10PM

You will note, as you noted earlier, that these produce the same time. The difference is that the first also has a -7:00. This does not indicate, as you intimated in your question, that time needs to have 7 hours removed to be shown as in the timezone, it instead indicates that the timestamp has already had 7 hours removed from Zulu.