How to convert python timestamp string to epoch?

前端 未结 6 1220
爱一瞬间的悲伤
爱一瞬间的悲伤 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:20

    Python 3.7+ The string format in question can be parsed by strptime:

    from datetime import datetime
    datetime.strptime("2009-03-08T00:27:31.807Z", '%Y-%m-%dT%H:%M:%S.%f%z')
    >>> datetime.datetime(2009, 3, 8, 0, 27, 31, 807000, tzinfo=datetime.timezone.utc)
    

    Another option using the built-in datetime.fromisoformat(): As mentioned in this thread linked by @jfs, fromisoformat() doesn't parse the 'Z' character to UTC although this is part of the RFC3339 definitions. A little work-around can make it work - some will consider this nasty but it's efficient after all.

    from datetime import datetime
    mytime = "2009-03-08T00:27:31.807Z"
    datetime.fromisoformat(mytime.replace("Z", "+00:00")).timestamp()
    >>> 1236472051.807
    

提交回复
热议问题