首页 > 解决方案 > 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')

标签: python-3.xdatetimepython-datetime

解决方案


要么导入你需要的模块,要么从模块中导入你需要类——不能同时导入。然后,根据您导入的内容编写代码:

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) 

推荐阅读