4

I have written this code to convert a unusual time into EPOCH:

x = 'Mon Jul 25 19:04:30 GMT+01:00 2016'
print(datetime.strptime(x, '%a %b %d %H:%M:%S %Z%z %Y').strftime('%s'))

However, it returns the error ValueError: time data 'Mon Jul 25 19:04:30 GMT+01:00 2016' does not match format '%a %b %d %H:%M:%S %Z%z %Y'

The problem is something to do with the timezone. What have I done wrong?

1
  • 1
    UTC offset must be in the form +HHMM or -HHMM, yours is +HH:MM. Commented Jan 21, 2017 at 18:34

2 Answers 2

3

Your timezone format has an extra : inside which causes the format mismatching error, you can remove the last : from the string firstly and then parse it:

import re
from datetime import datetime
x1 = re.sub(r":(?=[^:]+$)", "", x)   # remove the last semi colon

datetime.strptime(x1, '%a %b %d %H:%M:%S %Z%z %Y').strftime('%s')
# '1469487870'
Sign up to request clarification or add additional context in comments.

1 Comment

Interestingly, this works in Python3, but in Python2, this fails with: ValueError: 'z' is a bad directive in format '%a %b %d %H:%M:%S %Z%z %Y'
2

If you use dateutil instead of datetime.strptime it seems to work:

from dateutil import parser
parser.parse("Mon Jul 25 19:04:30 GMT+01:00 2016")
>> datetime.datetime(2016, 7, 25, 19, 4, 30, tzinfo=tzoffset(None, -3600))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.