如何将 python time.struct_time 对象转换为 ISO 字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19319370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:25:51  来源:igfitidea点击:

How do you convert a python time.struct_time object into a ISO string?

pythondatetimetime

提问by Antonio

I have a Python object:

我有一个 Python 对象:

time.struct_time(tm_year=2013, tm_mon=10, tm_mday=11, tm_hour=11, tm_min=57, tm_sec=12, tm_wday=4, tm_yday=284, tm_isdst=0)

And I need to get an ISO string:

我需要得到一个ISO 字符串

'2013-10-11T11:57:12Z'

How can I do that?

我怎样才能做到这一点?

采纳答案by Martijn Pieters

Using time.strftime()is perhaps easiest:

使用time.strftime()可能是最简单的:

iso = time.strftime('%Y-%m-%dT%H:%M:%SZ', timetup)

Demo:

演示:

>>> import time
>>> timetup = time.gmtime()
>>> time.strftime('%Y-%m-%dT%H:%M:%SZ', timetup)
'2013-10-11T13:31:03Z'

You can also use a datetime.datetime()object, which has a datetime.isoformat()method:

你也可以使用一个datetime.datetime()对象,它有一个datetime.isoformat()方法:

>>> from datetime import datetime
>>> datetime(*timetup[:6]).isoformat()
'2013-10-11T13:31:03'

This misses the timezone Zmarker; you could just add that.

这错过了时区Z标记;你可以加上那个。

回答by xuehui

iso = time.strftime('%Y-%m-%dT%H:%M:%SZ', timetup)

The last format charater ‘Z' is not necessary, such as

最后一个格式字符 'Z' 不是必需的,例如

iso = time.strftime('%Y-%m-%dT%H:%M:%S', timetup)

You will get time string like '2015-11-05 02:09:57'

您将获得类似 '2015-11-05 02:09:57' 的时间字符串