python-3.x - python中的UTC时间与datetime
问题描述
我怎样才能使用datetime.utcnow()
和datetime.date.today()
在一起?如果我正在运行代码 A,它会抛出错误,而代码 B 会抛出另一个错误。我想在我的代码中使用这两个。
一个
from datetime import datetime, timedelta
path = datetime.utcnow().strftime(f'{category}/%Y%m%d/%H:%M')
for year in range(2014, 2018):
for month in range(start_month_number, 13):
this_month = datetime.date.today().replace(year=year, month=month, day=1)
print(this_month)
error - AttributeError: 'method_descriptor' object has no attribute 'today'
乙
import datetime
path = datetime.utcnow().strftime(f'{category}/%Y%m%d/%H:%M')
for year in range(2014, 2018):
for month in range(start_month_number, 13):
this_month = datetime.date.today().replace(year=year, month=month, day=1)
print(this_month)
error- AttributeError: module 'datetime' has no attribute 'utcnow'
如果没有行,代码 B 运行良好 -->curryear = datetime.utcnow().strftime('%Y')
解决方案
要么导入你需要的模块,要么从模块中导入你需要的类——不能同时导入。然后,根据您导入的内容编写代码:
A:
from datetime import datetime, date
path = datetime.utcnow().strftime(f'{category}/%Y%m%d/%H:%M')
for year in range(2014, 2018):
for month in range(1, 13):
this_month = date(year=year, month=month, day=1)
print(this_month)
或 B:
import datetime
path = datetime.datetime.utcnow().strftime(f'{category}/%Y%m%d/%H:%M')
for year in range(2014, 2018):
for month in range(1, 13):
this_month = datetime.date(year=year, month=month, day=1)
print(this_month)
推荐阅读
- mongodb-query - 是否可以在一个 mongo 更新查询中将多个 objectId 设置为多个文档?
- python - 我可以像在 Java 中那样在 Python 中声明一个固定类型为整数的变量吗?
- python - 使用 CSV 数据作为 TensorFlow 推荐器的输入
- python - 获取数据框中每个数据的最小值
- c++ - 下级停止了,因为它收到了来自操作系统的信号。信号名称:SIGSEGV 信号含义:分段错误
- testing - 寻找一种能够记录选择器功能链的“合法”方式
- go - 类型定义是否有助于分配受限值?
- vue.js - 我无法运行带有 Nuxt 致命错误的 vue 项目
- mysql - 需要使用 SQL 从数据集中计算一些指标 - 单独的查询
- flutter - google_mobile_ads 0.13.0 插件横幅广告在颤振应用中调用 setstate 时自动重新加载