如何用Nanoseconds对象替换Python DateTimes中的datetime字段

2024-09-28 05:22:56 发布

您现在位置:Python中文网/ 问答频道 /正文

在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的一个子类,据说继承了它的所有函数,所以我尝试使用now()和replace()直接使用DatetimeWithNanoseconds

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

Tags: incoreapiclouddatetimevaluegoogle时间
1条回答
网友
1楼 · 发布于 2024-09-28 05:22:56

我贴出这个问题是因为我很难回答,所以我希望我的发现能帮助其他人

我找到的最佳解决方案是使用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})

相关问题 更多 >

    热门问题