Pymongo将时间戳记转换为日期作为新字段

时间:2019-06-13 02:27:20

标签: python mongodb date timestamp pymongo

我的收藏集中有很多实体,我必须在收藏中创建一个新的日期字段以用于将来的查询。

{'_id': ObjectId('5afea920d326051990a7f337'), 'created_at': 'Fri May 18 10:21:07 +0000 2018', 'timestamp_ms': '1526638867739'}
{'_id': ObjectId('5afea920d326051990a7f339'), 'created_at': 'Fri May 18 10:21:08 +0000 2018', 'timestamp_ms': '1526638868310'}
{'_id': ObjectId('5afea972d326051c5c05bc11'), 'created_at': 'Fri May 18 10:22:30 +0000 2018', 'timestamp_ms': '1526638950799'}
{'_id': ObjectId('5afea974d326051c5c05bc16'), 'created_at': 'Fri May 18 10:22:32 +0000 2018', 'timestamp_ms': '1526638952160'}
{'_id': ObjectId('5afea974d326051c5c05bc17'), 'created_at': 'Fri May 18 10:22:32 +0000 2018', 'timestamp_ms': '1526638952841'}

我需要将timestamp_ms转换成这样的日期格式:

{'_id': ObjectId('5afea920d326051990a7f337'), 'created_at': 'Fri May 18 10:21:07 +0000 2018', 'timestamp_ms': '1526638867739’, 'NewDate': '2018 05 18 10:21:07'}
{'_id': ObjectId('5afea920d326051990a7f339'), 'created_at': 'Fri May 18 10:21:08 +0000 2018', 'timestamp_ms': '1526638868310’, 'NewDate': '2018 05 18 10:21:08'}
{'_id': ObjectId('5afea972d326051c5c05bc11'), 'created_at': 'Fri May 18 10:22:30 +0000 2018', 'timestamp_ms': '1526638950799’, 'NewDate': '2018 05 18 10:22:30'}
{'_id': ObjectId('5afea974d326051c5c05bc16'), 'created_at': 'Fri May 18 10:22:32 +0000 2018', 'timestamp_ms': '1526638952160’, 'NewDate': '2018 05 18 10:22:32'}
{'_id': ObjectId('5afea974d326051c5c05bc17'), 'created_at': 'Fri May 18 10:22:32 +0000 2018', 'timestamp_ms': '1526638952841’, 'NewDate': '2018 05 18 10:22:32'}

我使用了以下代码(Python 3.6,pymongo 3.8,mongodb 4.0):

pipeline = [
    {
        '$addFields': {
            'newDate': {
                '$toDate': '$timestamp_ms'
            }
        }
    }
]
cursor = collection.aggregate(pipeline)

但是给出以下错误消息:pymongo.errors.OperationFailure: Error parsing date string '1526638867739'; 12: Unexpected character '9'

我不确定聚合是完成此任务的正确方法。 datetime.strptime()对于'created_at'可能更好,但我还没有弄清楚如何在db.Mycollection_update_many()中实现它。

2 个答案:

答案 0 :(得分:0)

在pymongo和mongodb 4.0中使用以下查询

db.test.aggregate(
    [
        {
            "$addFields": {
                "NewDate": {"$toDate": "$timestamp_ms"} 
            }
        },
        {
            "$out": "test"
        },
    ],
)

答案 1 :(得分:0)

我在MongoDB大学讨论论坛上从Kanika Singla那里得到了我的问题的答案。如果您有同样的问题,答案就在这里。

pipeline = [
    {
        '$project': {
            'yearMonthDayUTC': {
                '$convert': {
                    'to': 'double',
                    'input': '$timestamp_ms'
                }
            }
        }
    }, {
        '$addFields': {
            'newDate': {
                '$toDate': '$yearMonthDayUTC'
            }
        }
    }
]