简体   繁体   中英

Python `YYYY-MM-DD`

在Python中,从gtk.Calendar::get_date()的输出中获取RFC 3339 YYYY-MM-DD文本的最佳方法是什么?

Thanks to Mark and treeface for the solutions, but it seems I've invented a better one:

year, month, day = cal.get_date()
return '{0:04d}-{1:02d}-{2:02d}'.format(year, month+1, day)

This solution is shorter, easier to understand (in my opinion), and I believe takes less processing as it cuts out the stage where the tuple is converted into UNIX time.

According to the docs , the get_date returns a tuple of (year,month,day), where month 0 to 11 and day is 1 to 31, so:

import datetime
dtTuple = calControl.get_date()
dtObj = datetime.datetime(dtTuple[0], dtTuple[1] + 1, dtTuple[2]) #add one to month to make it 1 to 12
print dtObj.strftime("%Y-%m-%d")

This might be useful to you:

http://www.tutorialspoint.com/python/time_strftime.htm

I've also just looked around for this gtk get_date method and I was able to find some code that handles it like this:

//here replace "self.window.get_date()" with "gtk.Calendar::get_date()"
year, month, day = self.window.get_date()
mytime = time.mktime((year, month+1, day, 0, 0, 0, 0, 0, 0))
return time.strftime("%x", time.gmtime(mytime))

So just replace "%x" with "%G-%m-%d" and I think it would work. Or at least it's worth a try.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM