python - 在 Python 中解析和格式化来自 GitHub API 的日期

标签 python python-3.x github-api

<分区>

GitHub API 返回的当前值请求看起来像这样:

2013-09-12T22:42:02Z

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

最佳答案

从 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

关于python - 在 Python 中解析和格式化来自 GitHub API 的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18795713/

相关文章:

Python 类成员表现得好像它是静态的?

python - 在 Django 模板中显示 view.py 中的 url 变量

Python - 如何在 Windows 10 上完全卸载 Anaconda?

GitHub v3 API : How to create initial commit for my shiny new repository?

python - 将项目循环到 Django 1.8 模板中

github - 是否可以在github API中获取一个文件的提交历史记录?

python - 使用 Google Gears 离线访问 MoinMoin wiki

python - 通过子进程的 mysql 不起作用

Python3/MacOSX 集成到 pycharm

python - pygame 错误 : "ImportError: No module named ' pygame'"