How to convert python timestamp string to epoch?

前端 未结 6 1230
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-28 17:53

I have the following string:

mytime = \"2009-03-08T00:27:31.807Z\"

How do I convert it to epoch in python?

I tried:



        
6条回答
  •  臣服心动
    2020-12-28 18:21

    Code:

    import datetime
    epoch = datetime.datetime(1970, 1, 1)
    
    mytime = "2009-03-08T00:27:31.807Z"
    myformat = "%Y-%m-%dT%H:%M:%S.%fZ"
    mydt = datetime.datetime.strptime(mytime, myformat)
    val = (mydt - epoch).total_seconds()
    
    print(val)
    > 1236472051.81
    repr(val)
    > '1236472051.807'
    

    Notes:

    • When using time.strptime(), the returned time.struct_time does not support sub-second precision.
    • The %f format is for microseconds. When parsing it need not be the full 6 digits.

提交回复
热议问题