How to get UTC time in Python?

后端 未结 6 959
太阳男子
太阳男子 2020-12-02 10:47

I\'ve search a bunch on StackExchange for a solution but nothing does quite what I need. In JavaScript, I\'m using the following to calculate UTC time since Jan 1st 1970:

6条回答
  •  悲哀的现实
    2020-12-02 11:31

    In the form closest to your original:

    import datetime
    
    def UtcNow():
        now = datetime.datetime.utcnow()
        return now
    

    If you need to know the number of seconds from 1970-01-01 rather than a native Python datetime, use this instead:

    return (now - datetime.datetime(1970, 1, 1)).total_seconds()
    

    Python has naming conventions that are at odds with what you might be used to in Javascript, see PEP 8. Also, a function that simply returns the result of another function is rather silly; if it's just a matter of making it more accessible, you can create another name for a function by simply assigning it. The first example above could be replaced with:

    utc_now = datetime.datetime.utcnow
    

提交回复
热议问题