4

I'm pulling data from a London based service and they are giving me date&time info in London local time.So UTC in winter and BST(UTC+1) in summer.

Internally we use UTC for everything, in Python how do I convert the London stuff to UTC in a way that will account for daylight savings?

I appreciate that some times around the DST rollover are ambiguous, that's acceptable as long as it works the rest of the year.

For completeness, I'm getting the following info from them:

dt="2012-10-12T19:30:00"
lcnid="LDN"
locale="en-gb"
Gordon Wrigley
  • 11,015
  • 10
  • 48
  • 62
  • 1
    May be pytz is helpful, http://pytz.sourceforge.net/ – Rohan Oct 12 '12 at 09:02
  • maybe duplicate (answer here too) http://stackoverflow.com/questions/79797/how-do-i-convert-local-time-to-utc-in-python – Samuele Mattiuzzo Oct 12 '12 at 09:06
  • related: [Display the time in a different time zone](https://stackoverflow.com/q/1398674/10197418), [using Python 3.9's zoneinfo](https://stackoverflow.com/a/63628816/10197418) – FObersteiner Nov 11 '22 at 07:28

2 Answers2

9

You need to use a timezone object; these don't come with Python itself as the data changes too often. The pytz library is easily installed though.

Example conversion:

>>> import pytz
>>> import datetime
>>> bst = pytz.timezone('Europe/London')
>>> dt = datetime.datetime.strptime('2012-10-12T19:30:00', '%Y-%m-%dT%H:%M:%S')
>>> dt
datetime.datetime(2012, 10, 12, 19, 30)
>>> bst.localize(dt)
datetime.datetime(2012, 10, 12, 19, 30, tzinfo=<DstTzInfo 'Europe/London' BST+1:00:00 DST>)
>>> bst.localize(dt).astimezone(pytz.utc)
datetime.datetime(2012, 10, 12, 18, 30, tzinfo=<UTC>)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0
import pytz
utc = pytz.utc

print(utc.localize(datetime.datetime(2012,10,12,19,30,00)))
4b0
  • 21,981
  • 30
  • 95
  • 142
  • 1
    since you're using naive datetime, Python will assume local time, which is explicitly excluded in the question: "*in a specific local time (**not my local**)"*. Also, [pytz is deprecated](https://pypi.org/project/pytz-deprecation-shim/). – FObersteiner Nov 11 '22 at 07:25
  • [A code-only answer is not high quality](https://meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers). While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please [edit] your answer to include explanation and link to relevant documentation. – Muhammad Mohsin Khan Nov 16 '22 at 21:52