python 中的 UTC 时间和日期时间

UTC time in python with datetime

如何同时使用 datetime.utcnow()datetime.date.today()?如果我是 运行ning 代码 A,它会抛出错误,而代码 B 是另一个。我想在我的代码中同时使用这两个。

A

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'

B

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)

或乙:

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)