3

I have one date format "Mon, 15 Jun 2020 22:11:06 PT" I want to convert this format to unix timestamp.

I am using the following code ===>

news_date = datetime.strptime(news_date, '%a, %d %b %Y %H:%M:%S %Z')
news_date = calendar.timegm(news_date.utctimetuple())   

But gives the following error ===>

ValueError: time data 'Mon, 15 Jun 2020 22:11:06 PT' does not match format '%a, %d %b %Y %H:%M:%S %Z'

How can i solve it and get the unix timestamp from this?

1
  • Your problem is in strptime. Try to read the doc of such functions and solve this problem. Then go to next problem. One step at a time (if I remember correctly, in the same module you have also unix time [seconds from epoch)/ Commented Jun 19, 2020 at 11:51

1 Answer 1

3

2024 edit:

  • general note: with Python 3.9+, use zoneinfo. no need for a 3rd party lib anymore.
  • dateutil-specific: dateutil's parser can be fed with a mapping of abbreviations to IANA time zone names, to parse abbreviations. Example.

2020 answer:

%Z can't parse the time zone abbreviation PT - I suggest you skip parsing it and add it "manually" instead:

from datetime import datetime
import dateutil

news_date = "Mon, 15 Jun 2020 22:11:06 PT"

# parse string without the timezone:
news_date = datetime.strptime(news_date[:-3], '%a, %d %b %Y %H:%M:%S')

# add the timezone:
news_date = news_date.replace(tzinfo=dateutil.tz.gettz('US/Pacific'))

# extract POSIX (seconds since epoch):
news_date_posix = news_date.timestamp()
# 1592284266.0

if you have multiple strings with different timezones, you could use a dict to map the abbreviations to time zone names, e.g.

tzmapping = {'PT': 'US/Pacific'}
news_date = "Mon, 15 Jun 2020 22:11:06 PT"
# get appropriate timezone from string, according to tzmapping:
tz = dateutil.tz.gettz(tzmapping[news_date.split(' ')[-1]])
# parse string and add timezone:
news_date_datetime = datetime.strptime(news_date[:-3], '%a, %d %b %Y %H:%M:%S')
news_date_datetime = news_date_datetime.replace(tzinfo=tz)
Sign up to request clarification or add additional context in comments.

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.