Python: Converting from `datetime.datetime` to `time.time`

前端 未结 5 1876
醉话见心
醉话见心 2020-12-05 08:57

In Python, how do I convert a datetime.datetime into the kind of float that I would get from the time.time function?

5条回答
  •  旧时难觅i
    2020-12-05 09:45

    Given a datetime.datetime object dt, you could use

    (dt - datetime.datetime.utcfromtimestamp(0)).total_seconds()
    

    Example:

    >>> dt = datetime.datetime.now(); t = time.time()
    >>> t
    1320516581.727343
    >>> (dt - datetime.datetime.utcfromtimestamp(0)).total_seconds()
    1320516581.727296
    

    Note that the timedelta.total_seconds() method was introduced in Python 2.7.

提交回复
热议问题