What is the easiest way to get current GMT time in Unix timestamp format?

前端 未结 10 1216
失恋的感觉
失恋的感觉 2020-12-12 23:19

Python provides different packages (datetime, time, calendar) as can be seen here in order to deal with time. I made a big mistake by

相关标签:
10条回答
  • 2020-12-12 23:33
    from datetime import datetime as dt
    dt.utcnow().strftime("%s")
    

    Output:

    1544524990
    
    0 讨论(0)
  • Does this help?

    from datetime import datetime
    import calendar
    
    d = datetime.utcnow()
    unixtime = calendar.timegm(d.utctimetuple())
    print unixtime
    

    How to convert Python UTC datetime object to UNIX timestamp

    0 讨论(0)
  • 2020-12-12 23:49

    python2 and python3

    it is good to use time module

    import time
    int(time.time())
    

    1573708436

    you can also use datetime module, but when you use strftime('%s'), but strftime convert time to your local time!

    python2

    from datetime import datetime
    datetime.utcnow().strftime('%s')
    

    python3

    from datetime import datetime
    datetime.utcnow().timestamp()
    
    0 讨论(0)
  • 2020-12-12 23:51

    Or just simply using the datetime standard module

    In [2]: from datetime import timezone, datetime
       ...: int(datetime.now(tz=timezone.utc).timestamp() * 1000)
       ...: 
    Out[2]: 1514901741720
    

    You can truncate or multiply depending on the resolution you want. This example is outputting millis.

    If you want a proper Unix timestamp (in seconds) remove the * 1000

    0 讨论(0)
  • 2020-12-12 23:52
    #First Example:
    from datetime import datetime, timezone    
    timstamp1 =int(datetime.now(tz=timezone.utc).timestamp() * 1000)
    print(timstamp1)
    

    Output: 1572878043380

    #second example:
    import time
    timstamp2 =int(time.time())
    print(timstamp2)
    

    Output: 1572878043

    • Here, we can see the first example gives more accurate time than second one.
    • Here I am using the first one.
    0 讨论(0)
  • 2020-12-12 23:53
    import time
    
    int(time.time()) 
    

    Output:

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