【问题标题】:Convert Python datetime to firestore timestamp format将 Python 日期时间转换为 Firestore 时间戳格式
【发布时间】:2020-10-12 13:39:47
【问题描述】:

我一直在将我的代码结果上传到 Firestore 数据库,我需要检查在程序执行过程中何时满足某些条件。 目前,我一直将这些时间保存为从 datetime.now() 对象派生的字符串,所以我有类似的东西:

start_t = datetime.now().strftime("%Y_%m_%d_%H_%M_%S_%f")
stop_t = datetime.now().strftime("%Y_%m_%d_%H_%M_%S_%f")

经过一些阐述,这些事件被检查并且其中一些应该被上传到firestore数据库中的一个文档,现在我正在这样做:

db_ref.collection(u'events').document(doc_ID).set({
                u'start_time': start_t,
                u'stop_time': stop_t)
            }, merge=True)

我需要在文档中创建具有相应时间戳的字段,而不是像我目前所做的那样上传从日期时间派生的字符串...有什么方法可以自动完成吗?

【问题讨论】:

  • 通常,人们不会将时间戳作为格式化字符串存储在 Firestore 中。它们使用 Firestore 的原生时间戳字段类型,您可以使用原生日期对象或 Firestore SDK 的内置时间戳类型对其进行填充。

标签: python google-cloud-firestore


【解决方案1】:

我的错,我不知道我可以直接将 datetime 对象上传到 firestore,它会创建一个时间戳。

所以,我只是将字符串转换回日期时间(使用 datetime.strptime)并通过以下方式上传:

db_today_ref.collection(u'events').document(doc_ID).set({
    u'start_time': datetime.strptime(start_t, '%Y_%m_%d%H_%M_%S_%f'),
    u'stop_time': datetime.strptime(stop_t, '%Y_%m_%d%H_%M_%S_%f')
    }, merge=True)

【讨论】:

    猜你喜欢
    • 2020-02-23
    • 2016-11-26
    • 2019-02-25
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多