Converting datetime to POSIX time

后端 未结 6 1904
忘了有多久
忘了有多久 2021-01-31 02:14

How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don\'t seem to find any obv

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-31 02:16

    In python, time.time() can return seconds as a floating point number that includes a decimal component with the microseconds. In order to convert a datetime back to this representation, you have to add the microseconds component because the direct timetuple doesn't include it.

    import time, datetime
    
    posix_now = time.time()
    
    d = datetime.datetime.fromtimestamp(posix_now)
    no_microseconds_time = time.mktime(d.timetuple())
    has_microseconds_time = time.mktime(d.timetuple()) + d.microsecond * 0.000001
    
    print posix_now
    print no_microseconds_time
    print has_microseconds_time
    

提交回复
热议问题