Convert UTC datetime string to local datetime

后端 未结 13 954
醉话见心
醉话见心 2020-11-22 05:37

I\'ve never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I\'ve been running myself in circles. Lots of information on co

13条回答
  •  感情败类
    2020-11-22 05:48

    Consolidating the answer from franksands into a convenient method.

    import calendar
    import datetime
    
    def to_local_datetime(utc_dt):
        """
        convert from utc datetime to a locally aware datetime according to the host timezone
    
        :param utc_dt: utc datetime
        :return: local timezone datetime
        """
        return datetime.datetime.fromtimestamp(calendar.timegm(utc_dt.timetuple()))
    

提交回复
热议问题