How to convert local time string to UTC?

后端 未结 23 1163
离开以前
离开以前 2020-11-22 04:18

How do I convert a datetime string in local time to a string in UTC time?

I\'m sure I\'ve done this before, but can\'t find it and SO will hopefull

相关标签:
23条回答
  • 2020-11-22 05:10

    NOTE -- As of 2020 you should not be using .utcnow() or .utcfromtimestamp(xxx). As you've presumably moved on to python3,you should be using timezone aware datetime objects.

    >>> from datetime import timezone
    >>> dt_now = datetime.now(tz=timezone.utc)
    >>> dt_ts = datetime.fromtimestamp(1571595618.0, tz=timezone.utc)
    

    for details see: see: https://blog.ganssle.io/articles/2019/11/utcnow.html

    original answer (from 2010):

    The datetime module's utcnow() function can be used to obtain the current UTC time.

    >>> import datetime
    >>> utc_datetime = datetime.datetime.utcnow()
    >>> utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
    '2010-02-01 06:59:19'
    

    As the link mentioned above by Tom: http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/ says:

    UTC is a timezone without daylight saving time and still a timezone without configuration changes in the past.

    Always measure and store time in UTC.

    If you need to record where the time was taken, store that separately. Do not store the local time + timezone information!

    NOTE - If any of your data is in a region that uses DST, use pytz and take a look at John Millikin's answer.

    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:

    --> using local time as the basis for the offset value:

    >>> # Obtain the UTC Offset for the current system:
    >>> UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now()
    >>> local_datetime = datetime.datetime.strptime("2008-09-17 14:04:00", "%Y-%m-%d %H:%M:%S")
    >>> result_utc_datetime = local_datetime + UTC_OFFSET_TIMEDELTA
    >>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
    '2008-09-17 04:04:00'
    

    --> Or, from a known offset, using datetime.timedelta():

    >>> UTC_OFFSET = 10
    >>> result_utc_datetime = local_datetime - datetime.timedelta(hours=UTC_OFFSET)
    >>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
    '2008-09-17 04:04:00'
    

    UPDATE:

    Since python 3.2 datetime.timezone is available. You can generate a timezone aware datetime object with the command below:

    import datetime
    
    timezone_aware_dt = datetime.datetime.now(datetime.timezone.utc)
    

    If your ready to take on timezone conversions go read this:

    https://medium.com/@eleroy/10-things-you-need-to-know-about-date-and-time-in-python-with-datetime-pytz-dateutil-timedelta-309bfbafb3f7

    0 讨论(0)
  • 2020-11-22 05:13

    For getting around day-light saving, etc.

    None of the above answers particularly helped me. The code below works for GMT.

    def get_utc_from_local(date_time, local_tz=None):
        assert date_time.__class__.__name__ == 'datetime'
        if local_tz is None:
            local_tz = pytz.timezone(settings.TIME_ZONE) # Django eg, "Europe/London"
        local_time = local_tz.normalize(local_tz.localize(date_time))
        return local_time.astimezone(pytz.utc)
    
    import pytz
    from datetime import datetime
    
    summer_11_am = datetime(2011, 7, 1, 11)
    get_utc_from_local(summer_11_am)
    >>>datetime.datetime(2011, 7, 1, 10, 0, tzinfo=<UTC>)
    
    winter_11_am = datetime(2011, 11, 11, 11)
    get_utc_from_local(winter_11_am)
    >>>datetime.datetime(2011, 11, 11, 11, 0, tzinfo=<UTC>)
    
    0 讨论(0)
  • 2020-11-22 05:14

    First, parse the string into a naive datetime object. This is an instance of datetime.datetime with no attached timezone information. See documentation for datetime.strptime for information on parsing the date string.

    Use the pytz 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.

    Finally, use datetime.astimezone() method to convert the datetime to UTC.

    Source code, using local timezone "America/Los_Angeles", for the string "2001-2-3 10:11:12":

    import pytz, datetime
    local = pytz.timezone ("America/Los_Angeles")
    naive = datetime.datetime.strptime ("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")
    local_dt = local.localize(naive, is_dst=None)
    utc_dt = local_dt.astimezone(pytz.utc)
    

    From there, you can use the strftime() method to format the UTC datetime as needed:

    utc_dt.strftime ("%Y-%m-%d %H:%M:%S")
    
    0 讨论(0)
  • 2020-11-22 05:14

    One more example with pytz, but includes localize(), which saved my day.

    import pytz, datetime
    utc = pytz.utc
    fmt = '%Y-%m-%d %H:%M:%S'
    amsterdam = pytz.timezone('Europe/Amsterdam')
    
    dt = datetime.datetime.strptime("2012-04-06 10:00:00", fmt)
    am_dt = amsterdam.localize(dt)
    print am_dt.astimezone(utc).strftime(fmt)
    '2012-04-06 08:00:00'
    
    0 讨论(0)
  • 2020-11-22 05:14

    In python 3.9.0, after you've parsed your local time local_time into datetime.datetime object, just use local_time.astimezone(datetime.timezone.utc).

    0 讨论(0)
提交回复
热议问题