pythondatetimetzinfo

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

Solution

  • 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'>)