How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

前端 未结 13 1706
臣服心动
臣服心动 2020-11-22 07:49

I have a Python datetime object that I want to convert to unix time, or seconds/milliseconds since the 1970 epoch.

How do I do this?

13条回答
  •  忘掉有多难
    2020-11-22 08:12

    from datetime import datetime
    from calendar import timegm
    
    # Note: if you pass in a naive dttm object it's assumed to already be in UTC
    def unix_time(dttm=None):
        if dttm is None:
           dttm = datetime.utcnow()
    
        return timegm(dttm.utctimetuple())
    
    print "Unix time now: %d" % unix_time()
    print "Unix timestamp from an existing dttm: %d" % unix_time(datetime(2014, 12, 30, 12, 0))
    

提交回复
热议问题