在Python中将日期转换为字符串 [英] Converting date to string in Python

查看:253
本文介绍了在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'

这篇关于在Python中将日期转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆