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

Joel Goldstick joel.goldstick at gmail.com
Mon Oct 12 06:34:43 EDT 2020


On Mon, Oct 12, 2020 at 6:14 AM Steve <Gronicus at sga.ninja> wrote:
>
> At the top of my sample program, I have:
>
> import datetime
> from datetime import *

This second import tramples on the first.  What happens if you remove it?
>
> 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')

With the second import the above line will work if you do this:
dto = 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.
>
> ==================================================================
> Footnote:
> The human brain is one of the most complex things known to man.
> according to the human brain.
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays


More information about the Python-list mailing list