简体   繁体   English

Python中的Google应用引擎数据存储日期时间到目前为止?

[英]Google app engine datastore datetime to date in Python?

I've always hated the headache of managine dates, times, datetimes, and the various formats and conversions that are needed with them. 我一直很讨厌managine日期,时间,日期时间以及它们所需的各种格式和转换。 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: 我正在上一个关于使用谷歌应用引擎的在线课程,它说使用datetime属性,它返回格式的日期:

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. 我只想在不使用hacky正则表达式或字符串切片解决方案的情况下提取2012-06-25部分。

How do I parse this and convert it to the proper format? 我如何解析它并将其转换为正确的格式?

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')

If you are using a datetime property then the object you get back is a datetime instance not a string. 如果您使用的是datetime属性,那么您获取的对象是日期时间实例而不是字符串。

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. 请参阅print语句。 It does an implicit conversion to string. 它执行隐式转换为字符串。 If your outputting the datetime property value in a template, this is probably what is happening. 如果您在模板中输出datetime属性值,则可能发生了这种情况。

So in your code you should just use .date() method on the datetime object. 因此,在代码中,您应该在datetime对象上使用.date()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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