Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: converting date string to UTC

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
like image 798
Birchy Avatar asked Feb 05 '26 17:02

Birchy


2 Answers

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'>)
like image 58
Adam Avatar answered Feb 07 '26 06:02

Adam


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
like image 27
SteveJ Avatar answered Feb 07 '26 06:02

SteveJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!