简体   繁体   中英

UTC time in python with datetime

How can I use datetime.utcnow() and datetime.date.today() together? In case I am running code A it throws error and Code B other one. I want to use both of these in my code.

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'

Code B run fine in case there is no line -->curryear = datetime.utcnow().strftime('%Y')

Either import the module that you need, or the classes you need from the module - not both. Then, write your code according to what you have imported:

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)

or 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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM