在 Python 中将日期转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35018191/
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 15:52:56  来源:igfitidea点击:

Converting date to string in Python

pythonstringdate

提问by d0rmLife

I am using an API that requires date inputs to come in the form 'YYYY-MM-DD'- and yes, that's a string.

我使用的 API 需要日期输入的形式'YYYY-MM-DD'- 是的,这是一个字符串。

I am trying to write an iterative program that will cycle through some temporal data. The interval will always be one month.

我正在尝试编写一个迭代程序,该程序将循环遍历一些时态数据。间隔将始终为 1 个月。

Is there a nice way to convert a Python date object into the given format? I considered treating the year, month and day as integer inputs and incrementing the values as needed, but that's rather inelegant and requires significant if\elif\...\elseprogramming.

是否有将 Python 日期对象转换为给定格式的好方法?我考虑将年、月和日视为整数输入并根据需要增加值,但这相当不雅,并且需要大量if\elif\...\else编程。

采纳答案by gtlambert

Use the strftime()function of the datetime object:

使用strftime()datetime 对象的功能:

import datetime 

now = datetime.datetime.now()
date_string = now.strftime('%Y-%m-%d')
print(date_string)

Output

输出

'2016-01-26'

回答by Greg Hilston

Yes, there is already a module to handle this. See

是的,已经有一个模块来处理这个问题。看

https://docs.python.org/2/library/datetime.html

https://docs.python.org/2/library/datetime.html

Specifically,

具体来说,

date.isoformat() 

Which Returns a string representing the date in ISO 8601 format, ‘YYYY-MM-DD'.

返回一个字符串,表示 ISO 8601 格式的日期,'YYYY-MM-DD'。

For example, date(2002, 12, 4).isoformat() == '2002-12-04'.

例如,date(2002, 12, 4).isoformat() == '2002-12-04'。