3

I am parsing a 3rd party website HTML with dates and times which are always in UK time format, however they don't have any timezone info in the source. Converting the string to an object is easy enough using datetime.strptime(), but how do I add timezone info?

Ultimately, I need to convert these strings to a datetime object in UTC format. The code will always run on a PC which is timezone aware, i.e. datetime.now() will return UK time.

temp = '07/12/2017 13:30'
dt = datetime.strptime(temp, '%d/%m/%Y %H:%M')

Is there a nicer way to do this?

offset = datetime.now() - datetime.utcnow()
dt -= offset

2 Answers 2

3

Use pytz

import datetime
import pytz

temp = '07/12/2017 13:30'
dt = datetime.strptime(temp, '%d/%m/%Y %H:%M')
timezone = pytz.timezone("Etc/Greenwich")
d_aware = timezone.localize(dt)
d_aware.tzinfo
> <DstTzInfo 'Etc/Greenwich' PST-1 day, 16:00:00 STD>
d_aware
datetime.datetime(2017, 12, 7, 13, 30, tzinfo=<StaticTzInfo 'Etc/Greenwich'>)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the suggestions. Is it possible to do this without using a 3rd party library? I am wondering if there is a way to get the timezone offset of the PC (which will be UK time)?
Is your PC in UK time or is the site you are scraping UK time? The website might do localization and change it's server time to the time zone of your client (i.e. your scraper).
I'm located in the UK and am scraping a UK website. The reason I need to convert to UTC is because I'm using the scraped data to then interact with an API which defaults to UTC. I'm OK with using my own PC for the conversion as I'm confident that both are using UK timezones.
Why the restriction on not using pytz ? I would just use it.
2

There are some good libraries that make working with dates so much easier. I like dateparser, parsedatetime, and arrow;

import dateparser as dp
dt = dp.parse('07-12-2017 13:30 PST')
print (dt)

dt = dp.parse("Yesterday at 3:00am EST")
print(dt)


2017-07-12 13:30:00-08:00
2017-12-06 17:07:07.557109-05:00

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.