【问题标题】:how to replace datetime fields in Python DatetimeWithNanoseconds object如何替换 Python DatetimeWithNanoseconds 对象中的日期时间字段
【发布时间】:2021-04-16 22:51:52
【问题描述】:

在 Python 中,我需要在 google-cloud firestore 文档中设置时间戳字段。

我知道firestore 时间戳字段应使用google.api_core.datetime_helpers.DatetimeWithNanoseconds 设置,它是Datetime 的子类

我需要使用指定的分钟字段设置 now() 时间戳,并按以下给出的特定小时拨回

                'cursor_specs' = {
                    # specs to construct the next cursor
                    'minute_tick': 0,
                    'hours_dial_back': 1,
                },

因为DatetimeWithNanosecondsDatetime的子类,据说继承了它的所有功能,所以我尝试直接用DatetimeWithNanoseconds使用now()和replace()

from google.api_core.datetime_helpers import DatetimeWithNanoseconds

time_cursor = DatetimeWithNanoseconds.now().replace(minute=cursor_specs['minute_tick'],
                                    second=0, microsecond=0
                                ) - timedelta(hours=cursor_specs['hours_dial_back']

fs_model = fs.document(model["name"]).set({'time_cursor': time_cursor})

由于错误而失败

  File "/usr/local/lib/python3.8/site-packages/google/cloud/firestore_v1/_helpers.py", line 219, in <dictcomp>
    return {key: encode_value(value) for key, value in values_dict.items()}
  File "/usr/local/lib/python3.8/site-packages/google/cloud/firestore_v1/_helpers.py", line 173, in encode_value
    return document.Value(timestamp_value=value.timestamp_pb())
  File "/usr/local/lib/python3.8/site-packages/google/api_core/datetime_helpers.py", line 271, in timestamp_pb
    nanos = self._nanosecond or self.microsecond * 1000
AttributeError: _nanosecond

【问题讨论】:

标签: python datetime google-cloud-firestore python-datetime


【解决方案1】:

我发布这个问题是因为我一直在努力解决这个问题,所以我希望我的发现可以帮助其他人。

我找到的最佳解决方案是先使用 now() 和 replace() 设置一个常规的 Datetime 对象,然后将其转换为 DatetimeWithNanoseconds 对象。

from google.api_core.datetime_helpers import DatetimeWithNanoseconds
from google.api_core.datetime_helpers import to_rfc3339

time_cursor_in_datetime = datetime.now().replace(
                                minute=model['cursor']['next']['minute_tick'],
                                second=0, microsecond=0
                            ) - timedelta(hours=model['cursor']['next']['hours_dial_back'])

time_cursor =  DatetimeWithNanoseconds.from_rfc3339(
                                to_rfc3339(time_cursor_in_datetime)
                            )


fs_model = fs.document(model["name"]).set({'time_cursor': time_cursor})

【讨论】:

  • 与 RFC3339(我假设的字符串)的转换似乎是绕道而行。他们不是加了直接转换的方法吗?
  • 是的,确实是绕道而行。这是我上次查找时发现的最好的。真的很想知道是否有更好的方法。
猜你喜欢
  • 1970-01-01
  • 2011-12-02
  • 2020-04-18
  • 2023-04-09
  • 2015-09-21
  • 2013-12-20
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多