git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

What might cause my sample program to forget that already imported datetime?


Thank you, those two fixes took care of the problem.



Footnote:
The only time incorrectly is spelled incorrectly 
is when it is spelled "incorrectly".

-----Original Message-----
From: Python-list <python-list-bounces+gronicus=sga.ninja at python.org> On
Behalf Of Chris Angelico
Sent: Monday, October 12, 2020 6:37 AM
To: Python <python-list at python.org>
Subject: Re: What might cause my sample program to forget that already
imported datetime?

On Mon, Oct 12, 2020 at 9:14 PM Steve <Gronicus at sga.ninja> wrote:
>
> At the top of my sample program, I have:
>
> import datetime
> from datetime import *
>
> But import datetime also has to be entered on line 21 as shown.
> The error is printed at the bottom of the code.
> Why does the code seem to forget that I have already imported datetime?
> =============================================================
> import datetime
> from datetime import *
>
> d2 =  datetime.now()
> d2i = d2.isoformat()
>
> with open("TimeDate.txt", 'r') as infile:
>      for BottleInfo in infile: # loop to find each line in the file 
> for that dose
>        BottleInfo = BottleInfo.strip()
>
>        if ((BottleInfo[0:3]== "LBD")):
>             BottleData = BottleInfo[0:43].strip()
>
> BottleDataA = BottleData[4:14].strip() BottleDataB = 
> BottleData[16:30].strip() BottleDataC = BottleDataA + " " + 
> BottleDataB print("BottleDataC = <" + BottleDataC + ">")
> print()
> d1 = BottleDataC
>
> import datetime  #Why does this have to be here? line 21
>
> dto = datetime.datetime.strptime(d1, '%Y-%m-%d %H:%M:%S.%f') dti = 
> dto.isoformat()
>
> HoursDiff = int((d2-dto).total_seconds()/3600)
> print("HoursDiff = " + str(HoursDiff))
> print()
>
> TimeDateInfo=open("TimeDate.txt", "a") TimeDateInfo.write("{0:>5} 
> {1:>25} {2:>5}\n".format ("LBD", d2i, HoursDiff))
> TimeDateInfo.close()
>
> print("Done")
>
> """
> This is the error I get if I comment out line 21:
>
> Traceback (most recent call last):
>   File "F:/Med Insulin codes A/A TEST 10-07-2020/ReadWriteTimeDate 
> POSIX Samplea.py", line 38, in <module>
>     dto = datetime.datetime.strptime(d1, '%Y-%m-%d %H:%M:%S.%f')
> AttributeError: type object 'datetime.datetime' has no attribute
'datetime'
> """
> This code will be copied into another program as a function and the 
> presence of import datetime in line 21 causes another error.
>

The issue here is that you've done two different imports at the top:

import datetime
from datetime import *

These are incompatible with each other, so you're going to get issues.
I'd recommend doing just the first one, and then identifying d2 as
datetime.datetime.now() instead.

ChrisA
--
https://mail.python.org/mailman/listinfo/python-list