2017年2月22日 星期三

[ Python 常見問題 ] How can I convert a datetime object to milliseconds since epoch (unix time) in Python

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

How-To
It appears to me that the simplest way to do this is:
- test.py
  1. from datetime import datetime  
  2. import time  
  3.   
  4. epoch = datetime.datetime.utcfromtimestamp(0)  
  5.   
  6. def unix_time_millis(dt):  
  7.     return (dt - epoch).total_seconds() * 1000.0  
  8.   
  9. def unix_time_sec(dt):  
  10.     return (dt - epoch).total_seconds()  
Let's test it:
>>> from test import *
>>> now = datetime.now()
>>> now
datetime.datetime(2017, 2, 23, 0, 30, 54, 160342)
>>> e = unix_time_sec(now) # Retrieve seconds since epoch
>>> e
1487809854.160342
>>> dt = datetime(*time.localtime(e)[:-3]) # Translate seconds since epoch back to datetime object
>>> dt
datetime.datetime(2017, 2, 23, 8, 30, 54)


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...