【问题标题】:Cloud Firestore - Python - How to get local timezone in docs streamed with admin sdkCloud Firestore - Python - 如何在使用 admin sdk 流式传输的文档中获取本地时区
【发布时间】:2019-08-22 14:43:07
【问题描述】:

我是 firestore、python 和一般代码方面的真正新手,所以提前道歉。我正在使用管理 SDK 将 firestore 文档流式传输到文件中,并且想知道在流式传输文档时是否可以设置本地时区。

我知道 Firestore 只存储从纪元开始的偏移量。当我在控制台中查看它时,我会看到我的本地时区,并且我想在获取文档时设置相同的本地时区,但目前以 UTC 获取它们。

这是我的代码:

docs = db.collection_group(u'data').stream()   

with open(r'c:\file.txt', 'a') as file:
    for doc in docs:
        file.write(str(doc.to_dict()) + '\n')

我得到一个文件,其中包含所有文档作为单独的行中的字典,并带有 UTC 时间戳。例如:

{'action_name': 'NEW_LEVEL_VALUE', 'new_level': 0, 'timestamp': DatetimeWithNanoseconds(2019, 8, 22, 3, 12, 39, 263000, tzinfo=<UTC>)}

我找不到任何文档。任何想法将不胜感激。

【问题讨论】:

    标签: python firebase google-cloud-firestore


    【解决方案1】:

    DatetimeWithNanoseconds 基于标准库中的datetime。不同之处在于标准库不跟踪纳秒。

    您可以使用datetimestrftime() 方法来格式化时间戳:

    docs = db.collection_group(u'data').stream()   
    
    with open(r'c:\file.txt', 'a') as file:
        for doc in docs:
            doc_data = doc.to_dict()
            doc_data['timestamp'] = doc_data['timestamp'].strftime("%A, %d. %B %Y %I:%M%p")
            file.write(str(doc_data) + '\n')
    

    【讨论】:

    • 太棒了!谢谢!我找到了我需要使用本地时间的那个 astimezone(),并使用格式来显示它。
    【解决方案2】:

    由于您使用的是.to_dict,因此请在json.dumps() 函数中使用default=str 选项:

    import json
    
    # Firestore API code to get data 
    ...
    
    firestoreResult = docRef.get().to_dict()  # DatetimeWithNanoseconds format 
    
    outputWithTimestamp = json.dumps(, indent=4, default=str)
    
    

    所有DatetimeWithNanoseconds 现在将以格式显示 "my_timestamp": "2022-02-26 09:07:47.223000+00:00".

    to_dict() 的 Google Firestore 示例:https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 2018-03-15
      • 2021-04-02
      • 2018-12-05
      • 2020-05-02
      • 1970-01-01
      相关资源
      最近更新 更多