问题描述
我必须在 python 中处理表示 iso8601 时间戳的字符串.
因此,我的时间戳字符串采用以下形式:
timestamp = "2011-08-18T10:29:47+03:00"
目前我正在使用以下方法在 python 中转换它们:
timestamp = timestamp[:-6]时间戳 = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S")
但是这样我就丢失了所有关于时区的信息.我在 s-o 上看到了很多关于时间戳和 python 的例子,不幸的是没有人也保留时区,或者只是使用以下方法恢复时区延迟:
delay = 时间戳[-6:]
我也试过:
timestamp = "2011-08-18T10:29:47+03:00"时间戳 = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S%z")
但它回来了
ValueError: 'z' 是格式为 '%Y-%m-%dT%H:%M:%S%z' 的错误指令
你能提供一些见解吗?
python iso8601模块是用一个很棒的 parse_date 方法构建的,可以处理时区信息:
>>>进口iso8601>>>iso8601.parse_date("2007-01-25T12:00:00Z")datetime.datetime(2007, 1, 25, 12, 0, tzinfo=)>>>iso8601.parse_date("2011-08-18T10:29:47+03:00")datetime.datetime(2011, 8, 18, 10, 29, 47, tzinfo=)如果您想将其转换为其他时区,请使用 astimezone(tz) 方法
如果您需要获取 UTC 日期时间,您可以使用 utctimetuple() 方法.
I have to deal in python with strings representing iso8601 timestamps.
My timestamps string are therefore in the following form:
timestamp = "2011-08-18T10:29:47+03:00"
Currently I'm converting them in python using:
timestamp = timestamp[:-6]
timestamp = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S")
But in this way I lose all the information about the time zone.I have seen many examples here on s-o about timestamps and python, unfortunately no one was preserving the timezone as well, or just recover the time zone delay using:
delay = timestamp[-6:]
I have also tried:
timestamp = "2011-08-18T10:29:47+03:00"
timestamp = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S%z")
but it returned
ValueError: 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S%z'
Can you give some insight?
The python iso8601 module is built with a wonderful parse_date method that can handle timezone info :
>>> import iso8601
>>> iso8601.parse_date("2007-01-25T12:00:00Z")
datetime.datetime(2007, 1, 25, 12, 0, tzinfo=<iso8601.iso8601.Utc ...>)
>>> iso8601.parse_date("2011-08-18T10:29:47+03:00")
datetime.datetime(2011, 8, 18, 10, 29, 47, tzinfo=<FixedOffset '+03:00'>)
If you want to convert it in another timezone, use the astimezone(tz) method
If you need to get the UTC datetime you can use the utctimetuple() method.
这篇关于python:如何处理时间戳(ISO8601)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!