Convert to UTC Timestamp

前端 未结 4 1333
遥遥无期
遥遥无期 2021-01-08 00:09
//parses some string into that format.
datetime1 = datetime.strptime(somestring, \"%Y-%m-%dT%H:%M:%S\")

//gets the seconds from the above date.
timestamp1 = time.mk         


        
4条回答
  •  误落风尘
    2021-01-08 01:11

    I think you can use the utcoffset() method:

    utc_time = datetime1 - datetime1.utcoffset()
    

    The docs give an example of this using the astimezone() method here.

    Additionally, if you're going to be dealing with timezones, you might want to look into the PyTZ library which has lots of helpful tools for converting datetime's into various timezones (including between EST and UTC)

    With PyTZ:

    from datetime import datetime
    import pytz
    
    utc = pytz.utc
    eastern = pytz.timezone('US/Eastern')
    
    # Using datetime1 from the question
    datetime1 = datetime.strptime(somestring, "%Y-%m-%dT%H:%M:%S")
    
    # First, tell Python what timezone that string was in (you said Eastern)
    eastern_time = eastern.localize(datetime1)
    
    # Then convert it from Eastern to UTC
    utc_time = eastern_time.astimezone(utc)
    

提交回复
热议问题