Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting date to string in Python [duplicate]

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.

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.

like image 871
d0rmLife Avatar asked Jan 26 '16 15:01

d0rmLife


2 Answers

Use the strftime() function of the datetime object:

import datetime 

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

Output

'2016-01-26'
like image 171
gtlambert Avatar answered Oct 03 '22 08:10

gtlambert


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

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’.

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

like image 38
Greg Hilston Avatar answered Oct 03 '22 08:10

Greg Hilston