日期时间:处理数据类型

发布于 2025-01-13 15:23:57 字数 1137 浏览 0 评论 0原文

我的数据库中有一组商店产品,每个产品在 MongoDB 中都有唯一的 time_added 键,但是,我在解析它时遇到了问题。

我在代码中使用两种方法将 time_added 变量设置为数据库:

导入时间

ts = 时间.time()

类型 A: 生成 unix 时间戳,例如:

1646771033.712499

从日期时间导入日期时间
 
now = 日期时间.now()

类型B:在Mongo中生成一个datetime.datetime对象,例如:

2022-03-10T19:13:26.964+00:00

但是,我想解析代码中的两种类型,我尝试过:

today = datetime.now()
before = datetime.fromtimestamp(time_added)

today_validated = today.strftime("%Y-%m-%d")
before_validated = before.strftime("%Y-%m-%d")

today_date = s.datetime.strptime(today_validated, "%Y-%m-%d").date()
before_date = s.datetime.strptime(before_validated, "%Y-%m-%d").date()
delta = (today_date - before_date).days

print(delta)

但是,我收到错误:

2022-03-10 19:13:26.964000 is not a valid timestamp. int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime'

我理解这里的错误,我只是无法理解如何转换它,因为有些可能包含 A 型和 B 型

I have a set of shop products in my database, each with their unique time_added key in MongoDB, however, I run into a problem when parsing it.

I use two methods in my code to set the time_added variable to the db:

import time

ts = time.time()

Type A: Produces a unix timestamp, example:

1646771033.712499

and

from datetime import datetime
 
now = datetime.now()

Type B: Produces a datetime.datetime object in Mongo, example:

2022-03-10T19:13:26.964+00:00

However, I'd like to parse both types in my code, I tried:

today = datetime.now()
before = datetime.fromtimestamp(time_added)

today_validated = today.strftime("%Y-%m-%d")
before_validated = before.strftime("%Y-%m-%d")

today_date = s.datetime.strptime(today_validated, "%Y-%m-%d").date()
before_date = s.datetime.strptime(before_validated, "%Y-%m-%d").date()
delta = (today_date - before_date).days

print(delta)

However, I get an error:

2022-03-10 19:13:26.964000 is not a valid timestamp. int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime'

I understand the error here, I just can't get my head around converting this as some may contain Type A and some Type B

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文