从Python中的GitHub API解析并格式化日期

时间:2013-09-13 21:43:30

标签: python python-3.x github-api

GitHub API请求返回的当前值如下所示:

2013-09-12T22:42:02Z

如何解析此值并使其看起来更好?

1 个答案:

答案 0 :(得分:9)

GitHub API返回的日期格式为ISO 8601格式:YYYY-MM-DDTHH:MM:SSZ

要将该字符串转换为Python日期对象,请使用模块datetime

import datetime
date = datetime.datetime.strptime(<date_string>, "%Y-%m-%dT%H:%M:%SZ")

然后,您可以使用date.strftime()

将此字符串解析为您选择的格式
# Result: Thursday Sep 12, 2013 at 22:42 GMT
date.strftime('%A %b %d, %Y at %H:%M GMT')

或者如果您希望它更“自动”,指令%c将根据您系统的区域设置和语言设置自动选择日期/时间字符串。

# On my system, I get the following output:
#  Thu Sep 12 22:42:02 2013
date.strftime('%c')

如果您想自定义它,可以在此处找到完整的指令列表:http://docs.python.org/3/library/datetime.html#strftime-strptime-behavior