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

前端 未结 13 1611
臣服心动
臣服心动 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:01

    Here's another form of a solution with normalization of your time object:

    def to_unix_time(timestamp):
        epoch = datetime.datetime.utcfromtimestamp(0) # start of epoch time
        my_time = datetime.datetime.strptime(timestamp, "%Y/%m/%d %H:%M:%S.%f") # plugin your time object
        delta = my_time - epoch
        return delta.total_seconds() * 1000.0
    

提交回复
热议问题