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

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

问题描述:

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

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

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

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

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

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\...\else programming.

使用 strftime() 日期时间对象的函数:

Use the strftime() function of the datetime object:

import datetime 

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

输出

'2016-01-26'