Google app engine datastore datetime to date in Python?

半腔热情 提交于 2020-01-03 17:03:46

问题


I've always hated the headache of managine dates, times, datetimes, and the various formats and conversions that are needed with them. I'm taking an online course on using the google app engine and it says to use the datetime property, which is returning a date in the format:

2012-06-25 01:17:40.273000

I tried

datetime.strptime('2012-06-25 01:17:40.273000','%y-%m-%d %H:%M:%S')

but it didn't work..

I just want to extract the 2012-06-25 part without using a hacky regex or string slicing solution.

How do I parse this and convert it to the proper format?


回答1:


If you are using a datetime property then the object you get back is a datetime instance not a string.

On the console

>>> from datetime import datetime
>>> x = datetime.now()
>>> print x
2012-06-25 12:03:15.835467
>>> x.date()
datetime.date(2012, 6, 25)
>>> 
>>> print x.date()
2012-06-25
>>> 

See the print statement. It does an implicit conversion to string. If your outputting the datetime property value in a template, this is probably what is happening.

So in your code you should just use .date() method on the datetime object.




回答2:


Finally found it (shortly after asking the question, but I've been trying for the past hour)

datetime.strptime('2012-06-25 01:17:40.273000','%Y-%m-%d %H:%M:%S.%f')

What I wanted:

datetime.strptime('2012-06-25 01:17:40.273000','%Y-%m-%d %H:%M:%S.%f').strftime('%m-%d-%Y')


来源:https://stackoverflow.com/questions/11182638/google-app-engine-datastore-datetime-to-date-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!