简体   繁体   English

使用python在mongodb中保存日期

[英]saving date in mongodb using python

I have a field, 'date' that I take from a document.我有一个字段,我从文档中获取的'date' The field date has a value like this: "01.01.2014" .字段date具有如下值: "01.01.2014"

I'm saving this field into a mongo database like this:我将此字段保存到这样的 mongo 数据库中:

"date" : "01.01.2014",

If I split those parameters I have:如果我拆分这些参数,我有:

year ='2014' 
month ='01' 
day ='01' 

I want to save this field in proper type like datetime so how can I store it using those parameters?我想以适当的类型(如日期时间)保存此字段,那么如何使用这些参数存储它?

Use module datetime使用模块日期时间

your date object to be saved in mongoDB would be您要保存在 mongoDB 中的日期对象将是

myDateObject = datetime.datetime(year,month,day, 0 , 0)

use myDateObject to store as a value for date key in mongoDB.使用myDateObjectmyDateObject中存储为日期键的值。

Here year, month and day are expected to be integer.这里的年、月和日预计为整数。

As in your question, you can also use the date field to convert it to python datetime.与您的问题一样,您还可以使用日期字段将其转换为 python 日期时间。 Assuming date is in mm.dd.yyyy format, the code to convert date into datetime object is,假设日期为 mm.dd.yyyy 格式,则将日期转换为日期时间对象的代码为,

>>> datetime.datetime.strptime(date,"%m.%d.%Y")
datetime.datetime(2014, 1, 1, 0, 0)

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

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