JanvE
Posts: 7
Joined: Sun Feb 11, 2018 3:21 pm

Datetime issue

Wed May 05, 2021 5:19 pm

Dear all,
As a starter with Python I have the following issue.
Running this program results in:

d=datetime.datetime.strptime(tijd,'%H:%M')
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'

I think that is has something to do with the import but I don't know what.
I hope that some can help me out here.
Thank you,
Jan van Eeden
Netherlands

Code: Select all

 
 from datetime import datetime, timedelta
from datetime import *
tomorrow = datetime.now() + timedelta(days=+1)
tomorrow_formatted = tomorrow.strftime('%-d-%m-%y')

d=datetime.datetime.strptime(tijd,'%H:%M')
dnow=datetime.datetime.now()  

print(tomorrow_formatted)
print (dnow)

SurferTim
Posts: 2054
Joined: Sat Sep 14, 2013 9:27 am
Location: Miramar Beach, Florida

Re: Datetime issue

Wed May 05, 2021 5:40 pm

This runs ok. Couldn't figure out what "tijd" is.

Code: Select all

#!/usr/bin/env python3
from datetime import datetime, timedelta

tomorrow = datetime.now() + timedelta(days=+1)
tomorrow_formatted = tomorrow.strftime('%-d-%m-%y')

#d=datetime.datetime.strptime(tijd,'%H:%M')
dnow=datetime.now()  

print(tomorrow_formatted)
print (dnow)
My advice applies to RaspiOS only. Please mention if you use another OS.

JanvE
Posts: 7
Joined: Sun Feb 11, 2018 3:21 pm

Re: Datetime issue

Wed May 05, 2021 5:50 pm

Thank you very much Surfer Tim!

kheylen25
Posts: 15
Joined: Sun Apr 11, 2021 7:58 am

Re: Datetime issue

Wed May 05, 2021 6:29 pm

"tijd" is just a variable, which we don't know where it comes from, maybe from user input. Running only this snippet would result in an error as it is not declared. Try this code to convert to and back from datetime objects:

Code: Select all

from datetime import datetime

tijd = '11:45'
d = datetime.strptime(tijd,'%H:%M')

print(d)         # prints 1900-01-01 11:45:00
print(type(d))   # prints <class 'datetime.datetime'>

again_to_string = datetime.strftime(d, '%H:%M')
print(again_to_string)          # prints 11:45
print(type(again_to_string))    # prints <class 'str'>
Also, (they say that) it's good practice to store dates and times as datetime objects, as you can do all kind of calculations with it. Only convert to string when printing.

For timedelta objects, there's no need to add the plus sign, as you are just assigning a value to a keyword argument.

Code: Select all

from datetime import datetime, timedelta
tomorrow = datetime.now() + timedelta(days=1) 
print(tomorrow.strftime('%d-%m-%Y  %H:%M'))
(edit: forgot to import timedelta on second example)

Return to “Python”