<p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>

<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>

<p><strong>Clarification</strong>:  For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>

<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/" rel="noreferrer">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>

[{'answer_id': 79808, 'author': 'Chuck Callebs', 'author_id': 14877, 'author_profile': 'https://Stackoverflow.com/users/14877', 'pm_score': 5, 'selected': False, 'text': '<pre><code>def local_to_utc(t):\n    secs = time.mktime(t)\n    return time.gmtime(secs)\n\ndef utc_to_local(t):\n    secs = calendar.timegm(t)\n    return time.localtime(secs)\n</code></pre>\n\n<p>Source: <a href="http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html" rel="nofollow noreferrer">http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html</a></p>\n\n<p>Example usage from <a href="https://stackoverflow.com/users/8171/bd808">bd808</a>: If your source is a <code>datetime.datetime</code> object <code>t</code>, call as:</p>\n\n<pre><code>local_to_utc(t.timetuple())\n</code></pre>\n'}, {'answer_id': 79877, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 9, 'selected': False, 'text': '<p>First, parse the string into a naive datetime object. This is an instance of <code>datetime.datetime</code> with no attached timezone information. See its <a href="https://docs.python.org/3/library/datetime.html#available-types" rel="noreferrer">documentation</a>.</p>\n<p>Use the <a href="http://pytz.sourceforge.net/" rel="noreferrer"><code>pytz</code></a> module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime.</p>\n<p>Finally, use <code>datetime.astimezone()</code> method to convert the datetime to UTC.</p>\n<p>Source code, using local timezone &quot;America/Los_Angeles&quot;, for the string &quot;2001-2-3 10:11:12&quot;:</p>\n<pre><code>from datetime import datetime   \nimport pytz\n\nlocal = pytz.timezone(&quot;America/Los_Angeles&quot;)\nnaive = datetime.strptime(&quot;2001-2-3 10:11:12&quot;, &quot;%Y-%m-%d %H:%M:%S&quot;)\nlocal_dt = local.localize(naive, is_dst=None)\nutc_dt = local_dt.astimezone(pytz.utc)\n</code></pre>\n<p>From there, you can use the <code>strftime()</code> method to format the UTC datetime as needed:</p>\n<pre><code>utc_dt.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)\n</code></pre>\n'}, {'answer_id': 79913, 'author': 'Tom', 'author_id': 3715, 'author_profile': 'https://Stackoverflow.com/users/3715', 'pm_score': 7, 'selected': True, 'text': '<p>Thanks @rofly, the full conversion from string to string is as follows:</p>\n<pre><code>import time\ntime.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;, \n              time.gmtime(time.mktime(time.strptime(&quot;2008-09-17 14:04:00&quot;, \n                                                    &quot;%Y-%m-%d %H:%M:%S&quot;))))\n</code></pre>\n<p>My summary of the <code>time</code>/<code>calendar</code> functions:</p>\n<p><code>time.strptime</code><br />\nstring --&gt; tuple (no timezone applied, so matches string)</p>\n<p><code>time.mktime</code><br />\nlocal time tuple --&gt; seconds since epoch (always local time)</p>\n<p><code>time.gmtime</code><br />\nseconds since epoch --&gt; tuple in UTC</p>\n<p>and</p>\n<p><code>calendar.timegm</code><br />\ntuple in UTC --&gt; seconds since epoch</p>\n<p><code>time.localtime</code><br />\nseconds since epoch --&gt; tuple in local timezone</p>\n'}, {'answer_id': 1464261, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>How about - </p>\n\n<pre><code>time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))\n</code></pre>\n\n<p>if seconds is <code>None</code> then it converts the local time to UTC time else converts the passed in time to UTC.</p>\n'}, {'answer_id': 2175170, 'author': 'monkut', 'author_id': 24718, 'author_profile': 'https://Stackoverflow.com/users/24718', 'pm_score': 8, 'selected': False, 'text': '<p><strong>NOTE</strong> -- As of 2020 you should not be using <code>.utcnow()</code> or <code>.utcfromtimestamp(xxx)</code>.  As you\'ve presumably moved on to python3,you should be using timezone aware datetime objects.</p>\n<pre><code>&gt;&gt;&gt; from datetime import timezone\n&gt;&gt;&gt; \n&gt;&gt;&gt; # alternative to \'.utcnow()\'\n&gt;&gt;&gt; dt_now = datetime.datetime.now(datetime.timezone.utc)\n&gt;&gt;&gt;\n&gt;&gt;&gt; # alternative to \'.utcfromtimestamp()\'\n&gt;&gt;&gt; dt_ts = datetime.fromtimestamp(1571595618.0, tz=timezone.utc)\n</code></pre>\n<p>For details see: <a href="https://blog.ganssle.io/articles/2019/11/utcnow.html" rel="noreferrer">https://blog.ganssle.io/articles/2019/11/utcnow.html</a></p>\n<h2>original answer (from 2010):</h2>\n<p>The datetime module\'s <a href="http://docs.python.org/library/datetime.html#datetime.datetime.utcnow" rel="noreferrer">utcnow()</a> function can be used to obtain the current UTC time.</p>\n<pre><code>&gt;&gt;&gt; import datetime\n&gt;&gt;&gt; utc_datetime = datetime.datetime.utcnow()\n&gt;&gt;&gt; utc_datetime.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)\n\'2010-02-01 06:59:19\'\n</code></pre>\n<p>As the link mentioned above by Tom: <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/" rel="noreferrer">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>  says:</p>\n<blockquote>\n<p>UTC is a timezone without daylight saving time and still a timezone\nwithout configuration changes in the past.</p>\n<p><em>Always measure and store time in UTC</em>.</p>\n<p>If you need to record where the time was taken, store that separately.\n<em><strong>Do not</strong> store the local time + timezone information!</em></p>\n</blockquote>\n<p><strong>NOTE</strong> - If any of your data is in a region that uses DST, use <code>pytz</code> and take a look at John Millikin\'s answer.</p>\n<p>If you want to obtain the UTC time from a given string and your lucky enough to be in a region in the world that either doesn\'t use DST, or you have data that is only offset from UTC without DST applied:</p>\n<p>--&gt; using local time as the basis for the offset value:</p>\n<pre><code>&gt;&gt;&gt; # Obtain the UTC Offset for the current system:\n&gt;&gt;&gt; UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now()\n&gt;&gt;&gt; local_datetime = datetime.datetime.strptime(&quot;2008-09-17 14:04:00&quot;, &quot;%Y-%m-%d %H:%M:%S&quot;)\n&gt;&gt;&gt; result_utc_datetime = local_datetime + UTC_OFFSET_TIMEDELTA\n&gt;&gt;&gt; result_utc_datetime.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)\n\'2008-09-17 04:04:00\'\n</code></pre>\n<p>--&gt; Or, from a known offset, using datetime.timedelta():</p>\n<pre><code>&gt;&gt;&gt; UTC_OFFSET = 10\n&gt;&gt;&gt; result_utc_datetime = local_datetime - datetime.timedelta(hours=UTC_OFFSET)\n&gt;&gt;&gt; result_utc_datetime.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)\n\'2008-09-17 04:04:00\'\n</code></pre>\n<p>UPDATE:</p>\n<p>Since python 3.2 <code>datetime.timezone</code> is available.  You can generate a timezone aware datetime object with the command below:</p>\n<pre><code>import datetime\n\ntimezone_aware_dt = datetime.datetime.now(datetime.timezone.utc)\n</code></pre>\n<p>If your ready to take on timezone conversions go read this:</p>\n<p><a href="https://medium.com/@eleroy/10-things-you-need-to-know-about-date-and-time-in-python-with-datetime-pytz-dateutil-timedelta-309bfbafb3f7" rel="noreferrer">https://medium.com/@eleroy/10-things-you-need-to-know-about-date-and-time-in-python-with-datetime-pytz-dateutil-timedelta-309bfbafb3f7</a></p>\n'}, {'answer_id': 2347991, 'author': 'user235042', 'author_id': 235042, 'author_profile': 'https://Stackoverflow.com/users/235042', 'pm_score': 3, 'selected': False, 'text': '<p>if you prefer datetime.datetime:</p>\n\n<pre><code>dt = datetime.strptime("2008-09-17 14:04:00","%Y-%m-%d %H:%M:%S")\nutc_struct_time = time.gmtime(time.mktime(dt.timetuple()))\nutc_dt = datetime.fromtimestamp(time.mktime(utc_struct_time))\nprint dt.strftime("%Y-%m-%d %H:%M:%S")\n</code></pre>\n'}, {'answer_id': 4113872, 'author': 'Mohammad Efazati', 'author_id': 471397, 'author_profile': 'https://Stackoverflow.com/users/471397', 'pm_score': -1, 'selected': False, 'text': '<p>How about - </p>\n\n<pre><code>time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))\n</code></pre>\n\n<p>if seconds is <code>None</code> then it converts the local time to UTC time else converts the passed in time to UTC.</p>\n'}, {'answer_id': 4894920, 'author': 'Scipythonee', 'author_id': 600738, 'author_profile': 'https://Stackoverflow.com/users/600738', 'pm_score': 3, 'selected': False, 'text': "<pre><code>import time\n\nimport datetime\n\ndef Local2UTC(LocalTime):\n\n    EpochSecond = time.mktime(LocalTime.timetuple())\n    utcTime = datetime.datetime.utcfromtimestamp(EpochSecond)\n\n    return utcTime\n\n&gt;&gt;&gt; LocalTime = datetime.datetime.now()\n\n&gt;&gt;&gt; UTCTime = Local2UTC(LocalTime)\n\n&gt;&gt;&gt; LocalTime.ctime()\n\n'Thu Feb  3 22:33:46 2011'\n\n&gt;&gt;&gt; UTCTime.ctime()\n\n'Fri Feb  4 05:33:46 2011'\n</code></pre>\n"}, {'answer_id': 8068619, 'author': 'Dantalion', 'author_id': 384779, 'author_profile': 'https://Stackoverflow.com/users/384779', 'pm_score': 2, 'selected': False, 'text': '<p>For getting around day-light saving, etc.</p>\n\n<p>None of the above answers particularly helped me. The code below works for GMT.</p>\n\n<pre><code>def get_utc_from_local(date_time, local_tz=None):\n    assert date_time.__class__.__name__ == \'datetime\'\n    if local_tz is None:\n        local_tz = pytz.timezone(settings.TIME_ZONE) # Django eg, "Europe/London"\n    local_time = local_tz.normalize(local_tz.localize(date_time))\n    return local_time.astimezone(pytz.utc)\n\nimport pytz\nfrom datetime import datetime\n\nsummer_11_am = datetime(2011, 7, 1, 11)\nget_utc_from_local(summer_11_am)\n&gt;&gt;&gt;datetime.datetime(2011, 7, 1, 10, 0, tzinfo=&lt;UTC&gt;)\n\nwinter_11_am = datetime(2011, 11, 11, 11)\nget_utc_from_local(winter_11_am)\n&gt;&gt;&gt;datetime.datetime(2011, 11, 11, 11, 0, tzinfo=&lt;UTC&gt;)\n</code></pre>\n'}, {'answer_id': 8563126, 'author': 'Yarin', 'author_id': 165673, 'author_profile': 'https://Stackoverflow.com/users/165673', 'pm_score': 5, 'selected': False, 'text': '<p>I\'m having good luck with <a href="http://labix.org/python-dateutil" rel="noreferrer">dateutil</a> (which is widely recommended on SO for other related questions):</p>\n\n<pre><code>from datetime import *\nfrom dateutil import *\nfrom dateutil.tz import *\n\n# METHOD 1: Hardcode zones:\nutc_zone = tz.gettz(\'UTC\')\nlocal_zone = tz.gettz(\'America/Chicago\')\n# METHOD 2: Auto-detect zones:\nutc_zone = tz.tzutc()\nlocal_zone = tz.tzlocal()\n\n# Convert time string to datetime\nlocal_time = datetime.strptime("2008-09-17 14:02:00", \'%Y-%m-%d %H:%M:%S\')\n\n# Tell the datetime object that it\'s in local time zone since \n# datetime objects are \'naive\' by default\nlocal_time = local_time.replace(tzinfo=local_zone)\n# Convert time to UTC\nutc_time = local_time.astimezone(utc_zone)\n# Generate UTC time string\nutc_string = utc_time.strftime(\'%Y-%m-%d %H:%M:%S\')\n</code></pre>\n\n<p>(Code was derived from this answer to <a href="https://stackoverflow.com/a/4771733/165673">Convert UTC datetime string to local datetime</a>)</p>\n'}, {'answer_id': 10040725, 'author': 'Paulius Sladkevičius', 'author_id': 1316954, 'author_profile': 'https://Stackoverflow.com/users/1316954', 'pm_score': 4, 'selected': False, 'text': '<p>One more example with pytz, but includes localize(), which saved my day.</p>\n\n<pre><code>import pytz, datetime\nutc = pytz.utc\nfmt = \'%Y-%m-%d %H:%M:%S\'\namsterdam = pytz.timezone(\'Europe/Amsterdam\')\n\ndt = datetime.datetime.strptime("2012-04-06 10:00:00", fmt)\nam_dt = amsterdam.localize(dt)\nprint am_dt.astimezone(utc).strftime(fmt)\n\'2012-04-06 08:00:00\'\n</code></pre>\n'}, {'answer_id': 12059267, 'author': 'Cristian Salamea', 'author_id': 218604, 'author_profile': 'https://Stackoverflow.com/users/218604', 'pm_score': 2, 'selected': False, 'text': "<p>You can do it with:</p>\n\n<pre><code>&gt;&gt;&gt; from time import strftime, gmtime, localtime\n&gt;&gt;&gt; strftime('%H:%M:%S', gmtime()) #UTC time\n&gt;&gt;&gt; strftime('%H:%M:%S', localtime()) # localtime\n</code></pre>\n"}, {'answer_id': 12186921, 'author': 'Shu Wu', 'author_id': 1084497, 'author_profile': 'https://Stackoverflow.com/users/1084497', 'pm_score': 4, 'selected': False, 'text': '<p>I\'ve had the most success with <a href="https://dateutil.readthedocs.org/en/latest/relativedelta.html" rel="noreferrer">python-dateutil</a>:</p>\n\n<pre><code>from dateutil import tz\n\ndef datetime_to_utc(date):\n    """Returns date in UTC w/o tzinfo"""\n    return date.astimezone(tz.gettz(\'UTC\')).replace(tzinfo=None) if date.tzinfo else date\n</code></pre>\n'}, {'answer_id': 13084428, 'author': 'akaihola', 'author_id': 15770, 'author_profile': 'https://Stackoverflow.com/users/15770', 'pm_score': 5, 'selected': False, 'text': '<p>Here\'s a summary of common Python time conversions.</p>\n\n<p>Some methods drop fractions of seconds, and are marked with <em>(s)</em>. An explicit formula such as <code>ts = (d - epoch) / unit</code> can be used instead (thanks jfs).</p>\n\n<ul>\n<li>struct_time (UTC) → POSIX <em>(s)</em>:<br><code>calendar.timegm(struct_time)</code></li>\n<li>Naïve datetime (local) → POSIX <em>(s)</em>:<br><code>calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())</code><br>(exception during DST transitions, see comment from jfs)</li>\n<li>Naïve datetime (UTC) → POSIX <em>(s)</em>:<br><code>calendar.timegm(dt.utctimetuple())</code></li>\n<li>Aware datetime → POSIX <em>(s)</em>:<br><code>calendar.timegm(dt.utctimetuple())</code></li>\n<li>POSIX → struct_time (UTC, <em>s</em>):<br><code>time.gmtime(t)</code><br>(see comment from jfs)</li>\n<li>Naïve datetime (local) → struct_time (UTC, <em>s</em>):<br><code>stz.localize(dt, is_dst=None).utctimetuple()</code><br>(exception during DST transitions, see comment from jfs)</li>\n<li>Naïve datetime (UTC) → struct_time (UTC, <em>s</em>):<br><code>dt.utctimetuple()</code></li>\n<li>Aware datetime → struct_time (UTC, <em>s</em>):<br><code>dt.utctimetuple()</code></li>\n<li>POSIX → Naïve datetime (local):<br><code>datetime.fromtimestamp(t, None)</code><br>(may fail in certain conditions, see comment from jfs below)</li>\n<li>struct_time (UTC) → Naïve datetime (local, <em>s</em>):<br><code>datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)</code><br>(can\'t represent leap seconds, see comment from jfs)</li>\n<li>Naïve datetime (UTC) → Naïve datetime (local):<br><code>dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)</code></li>\n<li>Aware datetime → Naïve datetime (local):<br><code>dt.astimezone(tz).replace(tzinfo=None)</code></li>\n<li>POSIX → Naïve datetime (UTC):<br><code>datetime.utcfromtimestamp(t)</code></li>\n<li>struct_time (UTC) → Naïve datetime (UTC, <em>s</em>):<br><code>datetime.datetime(*struct_time[:6])</code><br>(can\'t represent leap seconds, see comment from jfs)</li>\n<li>Naïve datetime (local) → Naïve datetime (UTC):<br><code>stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)</code><br>(exception during DST transitions, see comment from jfs)</li>\n<li>Aware datetime → Naïve datetime (UTC):<br><code>dt.astimezone(UTC).replace(tzinfo=None)</code></li>\n<li>POSIX → Aware datetime:<br><code>datetime.fromtimestamp(t, tz)</code><br>(may fail for non-pytz timezones)</li>\n<li>struct_time (UTC) → Aware datetime <em>(s)</em>:<br><code>datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz)</code><br>(can\'t represent leap seconds, see comment from jfs)</li>\n<li>Naïve datetime (local) → Aware datetime:<br><code>stz.localize(dt, is_dst=None)</code><br>(exception during DST transitions, see comment from jfs)</li>\n<li>Naïve datetime (UTC) → Aware datetime:<br><code>dt.replace(tzinfo=UTC)</code></li>\n</ul>\n\n<p>Source: <a href="http://taaviburns.ca/presentations/what_you_need_to_know_about_datetimes/" rel="noreferrer">taaviburns.ca</a></p>\n'}, {'answer_id': 42348504, 'author': 'Yash', 'author_id': 2708266, 'author_profile': 'https://Stackoverflow.com/users/2708266', 'pm_score': 2, 'selected': False, 'text': '<p>Using <a href="http://crsmithdev.com/arrow/" rel="nofollow noreferrer">http://crsmithdev.com/arrow/</a></p>\n\n<pre><code>arrowObj = arrow.Arrow.strptime(\'2017-02-20 10:00:00\', \'%Y-%m-%d %H:%M:%S\' , \'US/Eastern\')\n\narrowObj.to(\'UTC\') or arrowObj.to(\'local\') \n</code></pre>\n\n<p>This library makes life easy :)</p>\n'}, {'answer_id': 48203190, 'author': 'spedy', 'author_id': 2115494, 'author_profile': 'https://Stackoverflow.com/users/2115494', 'pm_score': -1, 'selected': False, 'text': "<p>In python3:</p>\n\n<p><code>pip install python-dateutil</code></p>\n\n<pre><code>from dateutil.parser import tz\n\nmydt.astimezone(tz.gettz('UTC')).replace(tzinfo=None) \n</code></pre>\n"}, {'answer_id': 50138694, 'author': 'uclatommy', 'author_id': 4015330, 'author_profile': 'https://Stackoverflow.com/users/4015330', 'pm_score': 3, 'selected': False, 'text': '<h2>Simple</h2>\n\n<p>I did it like this:</p>\n\n<pre><code>&gt;&gt;&gt; utc_delta = datetime.utcnow()-datetime.now()\n&gt;&gt;&gt; utc_time = datetime(2008, 9, 17, 14, 2, 0) + utc_delta\n&gt;&gt;&gt; print(utc_time)\n2008-09-17 19:01:59.999996\n</code></pre>\n\n<h2>Fancy Implementation</h2>\n\n<p>If you want to get fancy, you can turn this into a functor:</p>\n\n<pre><code>class to_utc():\n    utc_delta = datetime.utcnow() - datetime.now()\n\n    def __call__(cls, t):\n        return t + cls.utc_delta\n</code></pre>\n\n<p>Result: </p>\n\n<pre><code>&gt;&gt;&gt; utc_converter = to_utc()\n&gt;&gt;&gt; print(utc_converter(datetime(2008, 9, 17, 14, 2, 0)))\n2008-09-17 19:01:59.999996\n</code></pre>\n'}, {'answer_id': 53760225, 'author': 'franksands', 'author_id': 289368, 'author_profile': 'https://Stackoverflow.com/users/289368', 'pm_score': 1, 'selected': False, 'text': '<p>I found the best answer on another question <a href="https://stackoverflow.com/a/1596308/289368">here</a>. It only uses python built-in libraries and does not require you to input your local timezone (a requirement in my case) </p>\n\n<pre><code>import time\nimport calendar\n\nlocal_time = time.strptime("2018-12-13T09:32:00.000", "%Y-%m-%dT%H:%M:%S.%f")\nlocal_seconds = time.mktime(local_time)\nutc_time = time.gmtime(local_seconds)\n</code></pre>\n\n<p>I\'m reposting the answer here since this question pops up in google instead of the linked question depending on the search keywords.</p>\n'}, {'answer_id': 62237615, 'author': 'tobixen', 'author_id': 1452887, 'author_profile': 'https://Stackoverflow.com/users/1452887', 'pm_score': 2, 'selected': False, 'text': '<p>I have this code in one of my projects:</p>\n\n<pre class="lang-py prettyprint-override"><code>from datetime import datetime\n## datetime.timezone works in newer versions of python\ntry:\n    from datetime import timezone\n    utc_tz = timezone.utc\nexcept:\n    import pytz\n    utc_tz = pytz.utc\n\ndef _to_utc_date_string(ts):\n    # type (Union[date,datetime]]) -&gt; str\n    """coerce datetimes to UTC (assume localtime if nothing is given)"""\n    if (isinstance(ts, datetime)):\n        try:\n            ## in python 3.6 and higher, ts.astimezone() will assume a\n            ## naive timestamp is localtime (and so do we)\n            ts = ts.astimezone(utc_tz)\n        except:\n            ## in python 2.7 and 3.5, ts.astimezone() will fail on\n            ## naive timestamps, but we\'d like to assume they are\n            ## localtime\n            import tzlocal\n            ts = tzlocal.get_localzone().localize(ts).astimezone(utc_tz)\n    return ts.strftime("%Y%m%dT%H%M%SZ")\n</code></pre>\n'}, {'answer_id': 62816943, 'author': 'Philipp', 'author_id': 2782049, 'author_profile': 'https://Stackoverflow.com/users/2782049', 'pm_score': 1, 'selected': False, 'text': '<p>If you already have a datetime object <code>my_dt</code> you can change it to UTC with:</p>\n<pre><code>datetime.datetime.utcfromtimestamp(my_dt.timestamp())\n</code></pre>\n'}, {'answer_id': 62840310, 'author': 'Alperen', 'author_id': 6900838, 'author_profile': 'https://Stackoverflow.com/users/6900838', 'pm_score': 0, 'selected': False, 'text': "<p><strong>Briefly</strong>, to convert any <code>datetime</code> date to UTC time:</p>\n<pre><code>from datetime import datetime\n\ndef to_utc(date):\n    return datetime(*date.utctimetuple()[:6])\n</code></pre>\n<hr />\n<p>Let's explain with an example. First, we need to create a <code>datetime</code> from the string:</p>\n<pre><code>&gt;&gt;&gt; date = datetime.strptime(&quot;11 Feb 2011 17:33:54 -0800&quot;, &quot;%d %b %Y %H:%M:%S %z&quot;)\n</code></pre>\n<p>Then, we can call the function:</p>\n<pre><code>&gt;&gt;&gt; to_utc(date)\ndatetime.datetime(2011, 2, 12, 1, 33, 54)\n</code></pre>\n<p>Step by step how the function works:</p>\n<pre><code>&gt;&gt;&gt; date.utctimetuple()\ntime.struct_time(tm_year=2011, tm_mon=2, tm_mday=12, tm_hour=1, tm_min=33, tm_sec=54, tm_wday=5, tm_yday=43, tm_isdst=0)\n&gt;&gt;&gt; date.utctimetuple()[:6]\n(2011, 2, 12, 1, 33, 54)\n&gt;&gt;&gt; datetime(*date.utctimetuple()[:6])\ndatetime.datetime(2011, 2, 12, 1, 33, 54)\n</code></pre>\n"}, {'answer_id': 64097432, 'author': 'FObersteiner', 'author_id': 10197418, 'author_profile': 'https://Stackoverflow.com/users/10197418', 'pm_score': 4, 'selected': False, 'text': '<p>An option available since Python 3.6: <code>datetime.astimezone(tz=None)</code> can be used to get an aware datetime object representing local time <a href="https://docs.python.org/3/library/datetime.html#datetime.datetime.astimezone" rel="noreferrer">(docs)</a>. This can then easily be converted to UTC.</p>\n<pre><code>from datetime import datetime, timezone\ns = &quot;2008-09-17 14:02:00&quot;\n\n# to datetime object:\ndt = datetime.fromisoformat(s) # Python 3.7\n\n# I\'m on time zone Europe/Berlin; CEST/UTC+2 during summer 2008\ndt = dt.astimezone()\nprint(dt)\n# 2008-09-17 14:02:00+02:00\n\n# ...and to UTC:\ndtutc = dt.astimezone(timezone.utc)\nprint(dtutc)\n# 2008-09-17 12:02:00+00:00\n</code></pre>\n<p>Side-Note: While the described conversion to UTC works perfectly fine, <code>.astimezone()</code> sets <code>tzinfo</code> of the datetime object to a timedelta-derived timezone - so don\'t expect any &quot;DST-awareness&quot; from it.</p>\n'}, {'answer_id': 64626046, 'author': 'Zisheng Ye', 'author_id': 8102752, 'author_profile': 'https://Stackoverflow.com/users/8102752', 'pm_score': 2, 'selected': False, 'text': "<p>In python 3.9.0, after you've parsed your local time <code>local_time</code> into <code>datetime.datetime</code> object, just use <code>local_time.astimezone(datetime.timezone.utc)</code>.</p>\n"}, {'answer_id': 69031527, 'author': 'Lalit Sharma', 'author_id': 7756843, 'author_profile': 'https://Stackoverflow.com/users/7756843', 'pm_score': 1, 'selected': False, 'text': '<p>For anyone who is confused with the most upvoted answer. You can convert a datetime string to utc time in python by generating a datetime object and then you can use astimezone(pytz.utc) to get datetime in utc.</p>\n<p>For eg.</p>\n<p>let say we have local datetime string as <code>2021-09-02T19:02:00Z</code> in isoformat</p>\n<p>Now to convert this string to utc datetime. we first need to generate datetime object using this string by</p>\n<p><code>dt = datetime.strptime(dt,\'%Y-%m-%dT%H:%M:%SZ\')</code></p>\n<p>this will give you python datetime object, then you can use <code>astimezone(pytz.utc)</code> to get utc datetime like</p>\n<p><code>dt = datetime.strptime(dt,\'%Y-%m-%dT%H:%M:%SZ\') dt = dt.astimezone(pytz.utc)</code></p>\n<p>this will give you datetime object in utc, then you can convert it to string using <code>dt.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)</code></p>\n<p>full code eg:</p>\n<pre><code>from datetime import datetime\nimport pytz\n\ndef converLocalToUTC(datetime, getString=True, format=&quot;%Y-%m-%d %H:%M:%S&quot;):\n    dt = datetime.strptime(dt,\'%Y-%m-%dT%H:%M:%SZ\')\n    dt = dt.astimezone(pytz.utc)\n    \n    if getString:\n        return dt.strftime(format)\n    return dt\n</code></pre>\n<p>then you can call it as</p>\n<p><code>converLocalToUTC(&quot;2021-09-02T19:02:00Z&quot;)</code></p>\n<p>took help from\n<a href="https://stackoverflow.com/a/79877/7756843">https://stackoverflow.com/a/79877/7756843</a></p>\n'}, {'answer_id': 69261133, 'author': 'Bryce', 'author_id': 11804374, 'author_profile': 'https://Stackoverflow.com/users/11804374', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s an example with the native <a href="https://docs.python.org/3/library/zoneinfo.html" rel="nofollow noreferrer">zoneinfo</a> module in <strong>Python3.9</strong>:</p>\n<pre class="lang-py prettyprint-override"><code>from datetime import datetime\nfrom zoneinfo import ZoneInfo\n\n# Get timezone we\'re trying to convert from\nlocal_tz = ZoneInfo(&quot;America/New_York&quot;)\n# UTC timezone\nutc_tz = ZoneInfo(&quot;UTC&quot;)\n\ndt = datetime.strptime(&quot;2021-09-20 17:20:00&quot;,&quot;%Y-%m-%d %H:%M:%S&quot;)\ndt = dt.replace(tzinfo=local_tz)\ndt_utc = dt.astimezone(utc_tz)\n\nprint(dt.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;))\nprint(dt_utc.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;))\n</code></pre>\n<p>This may be preferred over just using <code>dt.astimezone()</code> in situations where the timezone you\'re converting from isn\'t reflective of your system\'s local timezone. Not having to rely on external libraries is nice too.</p>\n<p><strong>Note</strong>: This may not work on Windows systems, since <a href="https://docs.python.org/3/library/zoneinfo.html#data-sources" rel="nofollow noreferrer">zoneinfo relies on an IANA database</a> that may not be present. The <a href="https://tzdata.readthedocs.io/en/latest/" rel="nofollow noreferrer">tzdata</a> package can be installed as a workaround. It\'s a first-party package, but is not in the standard library.</p>\n'}]
['https://Stackoverflow.com/questions/79797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3715/']