Re: Top level of a recursive function

2022-12-15 Thread Peter Otten

On 13/12/2022 15:46, Michael F. Stemper wrote:

It's easy enough -- in fact necessary -- to handle the bottom
level of a function differently than the levels above it. What
about the case where you want to handle something differently
in the top level than in lower levels? Is there any way to tell
from within a function that it wasn't invoked by itself?

I've come up with a hack to support different processing, by
use of an extra argument, as shown in this simplified example:

def fred(cf,toplevel=True):
   x = cf[0]
   if len(cf)>1:
     if toplevel:
   return x + fred(cf[1:],False)
     else:
   return "(" + x + fred(cf[1:],False) + ")"
   else:
     if toplevel:
   return x
     else:
   return "(" + x + ")"

Aside from being ugly, this lets the caller diddle with "toplevel",
which shouldn't really be externally modifiable.

Are there better ways to do this?


For adepts of functional programming the above is a "fold right"
operation, first hit for "foldr in python":

https://burgaud.com/foldl-foldr-python

With that

>>> from functools import reduce
>>> def foldr(func, items):
return reduce(lambda x, y: func(y, x), items[::-1])

your problem reduces ;) to

>>> foldr("{0}({1})".format, [1,2,3,4])
'1(2(3(4)))'

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


Re: Keeping a list of records with named fields that can be updated

2022-12-15 Thread Peter Otten

On 14/12/2022 19:50, songbird wrote:


   I'm relatively new to python but not new to programming in general.

   The program domain is accounting and keeping track of stock trades and other 
related information (dates, cash accounts, interest, dividends, transfers of 
funds, etc.)

   Assume that all data is CSV format.  There are multiple files.

   Assume there is a coherent starting point and that all data is in order.

   Assume each line contains a description.  The description determines what 
the line is.  The number of fields in the line does not change within the data 
file but it may happen that later lines in other files may be different other 
than the fact that they all must contain a description.

   All descriptions are deterministic (none are recursive or referencing things 
from the future).  All things referenced in the description which do not 
already exist are added to a list (or perhaps more than one in a few cases) and 
may contain some basic information (the date, how many and for how much, or a 
total amount or a fee or ...)  If the field of the line isn't a number it is 
either a symbol or a description.

   A default action is simply to keep most parts of the line and to adjust any 
totals of a previously seen description that matches by whatever amounts are on 
the line.  The key is the description.

   I've already written one program based upon the files I already have which 
works but what happens is that new descriptions are added (new accounts, new 
stocks, etc.) and I don't want to have to write new code manually every time a 
description changes.

   I started using named tuples (it works for reading in the files and 
accessing the fields) but I cannot update those so I need to use something else 
to give me the list of unique descriptions and fields that I need to update.  
I've not gotten beyond that yet as I'm still learning.

   Suggestions?

   Thanks!  :)


While I think what you need is a database instead of the collection of
csv files the way to alter namedtuples is to create  a new one:

>>> from collections import namedtuple
>>> Row = namedtuple("Row", "foo bar baz")
>>> row = Row(1, 2, 3)
>>> row._replace(bar=42)
Row(foo=1, bar=42, baz=3)

An alternative would be dataclasses where basic usage is just as easy:

>>> from dataclasses import make_dataclass
>>> Row = make_dataclass("Row", "foo bar baz".split())
>>> row = Row(1, 2, 3)
>>> row
Row(foo=1, bar=2, baz=3)
>>> row.bar = 42
>>> row
Row(foo=1, bar=42, baz=3)


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


Re: Keeping a list of records with named fields that can be updated

2022-12-15 Thread Weatherby,Gerard
I have a lot of NamedTuples in my codebase, and I now add new ones never. They 
were a good option prior to Python 3.7 but dataclasses are much easier to work 
with and are almost a drop-in substitute.

A combination of a default dictionary and a dataclass might meet your needs:



import collections
from dataclasses import dataclass


@dataclass
class AccountingEntry:
description: str
# other fields


ledger = collections.defaultdict(list)

for ae in get_accounting_entries():
ledger[ae.description] = ae



From: Python-list  on 
behalf of songbird 
Date: Wednesday, December 14, 2022 at 10:38 PM
To: python-list@python.org 
Subject: Keeping a list of records with named fields that can be updated
*** Attention: This is an external email. Use caution responding, opening 
attachments or clicking on links. ***

  I'm relatively new to python but not new to programming in general.

  The program domain is accounting and keeping track of stock trades and other 
related information (dates, cash accounts, interest, dividends, transfers of 
funds, etc.)

  Assume that all data is CSV format.  There are multiple files.

  Assume there is a coherent starting point and that all data is in order.

  Assume each line contains a description.  The description determines what the 
line is.  The number of fields in the line does not change within the data file 
but it may happen that later lines in other files may be different other than 
the fact that they all must contain a description.

  All descriptions are deterministic (none are recursive or referencing things 
from the future).  All things referenced in the description which do not 
already exist are added to a list (or perhaps more than one in a few cases) and 
may contain some basic information (the date, how many and for how much, or a 
total amount or a fee or ...)  If the field of the line isn't a number it is 
either a symbol or a description.

  A default action is simply to keep most parts of the line and to adjust any 
totals of a previously seen description that matches by whatever amounts are on 
the line.  The key is the description.

  I've already written one program based upon the files I already have which 
works but what happens is that new descriptions are added (new accounts, new 
stocks, etc.) and I don't want to have to write new code manually every time a 
description changes.

  I started using named tuples (it works for reading in the files and accessing 
the fields) but I cannot update those so I need to use something else to give 
me the list of unique descriptions and fields that I need to update.  I've not 
gotten beyond that yet as I'm still learning.

  Suggestions?

  Thanks!  :)


  songbird
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!ndkoYjlClLoELvhzTpXFZEtJ70fXjdFllo-ce0fJ4f0AdRLQXvryO11ZSJ16tf-Ke-pko3kmBxW1cesvrQAQUQ$
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Subtracting dates to get hours and minutes

2022-12-15 Thread Gronicus
So far so good , I can now use a variable in datetime.datetime but it only
works if I hard-code the time/date information. Now I want to have the code
read from a file but I get: TypeError: function takes at most 9 arguments
(26 given)

I figure that the structure in the file is incorrect. What should it be? The
entry in the file is (2022, 12, 13,  5,  3, 30) but when my program tries to
use it I get the error.

The program is a bit more sophisticated now but here is the update with a
sample of the SPECIFICATIONS.txt file:
=

# This program compares two Timedate values, subtracts the two and
# converts the difference to seconds and hours.
#

#  %A Monday#  %a Mon   #  %B January   #  %b Jan
#  %d 05 day#  %m month as 01   #  %Y 2020  #  %y 20
#  %H 24#  %I 12#  %M 30 min#  %S Seconds

import time
import datetime
from time import gmtime, strftime ##define strftime as time/date right now
# ==

def GetSpecByItem(GetThisOne):  #get line by item in column 4 - 7
ItemValue = "--"

with open("SPECIFICATIONS.txt" , 'r') as infile:
 for lineEQN in infile: # loop to find each line in the file for that
dose
if ((lineEQN[4:7]== GetThisOne)):
   ItemValue = lineEQN[30:60].strip()   # Just the Data
return(ItemValue)

"""
SPECIFICATIONS.txt

IYf HRB Humalog R Date   (2018, 12, 4, 10,  7, 00)   ##
IYf HRG Humulin R Date   (2022, 12, 13,  5,  3, 30)  ##
"""
# == Main() ==
print()
Startt = "404"
Stopp  = "404"

Answer = "Y"
Answer = input("Run test A? (" + Answer + ")" )

if Answer == "Y" or Answer == "y" or Answer == "":
   print()
   print(" Running Test A:")
#   Year  Mth Day Hour Min Sec
   Startt  =   2018, 12, 4, 10,  7, 00  
   Stopp   =   2022, 12, 12, 1, 15, 30
   NowTime =   2022, 12, 14, 21, 15, 30
else:
   print(" Running Test B:")
   Startt = GetSpecByItem("HRG")
   Stopp =  GetSpecByItem("HRB")
   NowTime = strftime("(%Y, %m, %d, %H, %M, %S)")
   
print()
print("55NowTime = " + str(NowTime))
print("56 Startt = " + str(Startt))
print("57  Stopp = " + str(Stopp))
print()

NowTime =  datetime.datetime(*NowTime)
Startt =   datetime.datetime(*Startt)
Stopp =datetime.datetime(*Stopp)

#Start == Startt  # True" 
#print("Startt test = " + Start)
# =
print()
c = NowTime - Stopp 
minutes = c.total_seconds() / 60 
minutes = c.seconds / 60
hours = 0

while (minutes > 59):
minutes = minutes - 60
hours += 1
minutes = round(minutes)
print ("77 Hours = <" + str(hours) + ">")
print ("78 Minutes =   <" + str(minutes) + ">")
if hours > 7:
print(" Time to inject Humulin R u500.")

pause = input("Pause")
# ==


-Original Message-
From: Python-list  On
Behalf Of Thomas Passin
Sent: Tuesday, December 13, 2022 11:20 PM
To: python-list@python.org
Subject: Re: Subtracting dates to get hours and minutes

Your problem is that datetime.datetime does not accept a tuple as an
argument.  It expects an integer value for the first argument, but you
supplied a tuple.  In Python, you can use a sequence (e.g., tuple or
list) the way you want by prefixing it with an asterisk.  This causes the
sequence of items to be treated as individual arguments. So:

Startt = datetime.datetime(2022, 12, 13,  5,  3, 30)
st1 = (2022, 12, 13,  5,  3, 30)
dts1 = datetime.datetime(*st1)  # NOT datetime.datetime(st1)
dts1 == Startt  # True

On 12/13/2022 10:43 PM, Gronicus@SGA.Ninja wrote:
>   As is, Test A works.
>   Comment out Test A and uncomment Test B it fails.
>   In Test B, I move the data into a variable resulting with the report:
>  "TypeError: an integer is required (got type tuple)
> 
> How do I fix this?
> 
> #-
> 
> import datetime
> #=
> # Test A   Hard coded Date/Time
> Startt = datetime.datetime(2022, 12, 13,  5,  3, 30) Stopp =  
> datetime.datetime(2022, 12, 12, 21, 15, 30)
> 
> # =
> # Test B   Date/Time data as a variable
> #Startt = (2022, 12, 13,  5,  3, 30)
> #Stopp =  (2022, 12, 12, 21, 15, 30)
> 
> #Startt = datetime.datetime(Startt)
> #Stopp =  datetime.datetime(Stopp)
> 
> # =
> c = Startt - Stopp
> minutes = c.total_seconds() / 60
> minutes = c.seconds / 60
> hours = 0
> 
> while (minutes > 59):
>  minutes = minutes - 60
>  hours += 1
> minutes = round(minutes)
> print()
> print ("   Hours =  <" + str(hours) + ">")
> print (" Minutes =  <" + str(minutes) + ">")
> 
> # 
> ---

Re: Single line if statement with a continue

2022-12-15 Thread Chris Green
Thomas Passin  wrote:
>I personally tend to use
> 
> if test: return
> 
> even inside larger blocks.

I always try to avoid multiple returns from functions/methods, as soon
as things get complex it's all to easy to miss clean-up etc.

"No multiple returns" is often found in programming guidelines.

-- 
Chris Green
·
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Single line if statement with a continue

2022-12-15 Thread Cecil Westerhof via Python-list
r...@zedat.fu-berlin.de (Stefan Ram) writes:

>>"No multiple returns" is often found in programming guidelines.
>
>   I religiously followed that when I did more C programming
>   than today. Then, I read an article about how the result
>   pattern makes functions measurably slower. (It should not
>   with an optimizing compiler, but it did due to those
>   measurements. Can't find that article now, though.)

That makes me think about the quote from Edsger W. Dijkstra about the
go to statement:
Please do not fall into the trap of believing that I am terribly
dogmatic about the go to statement. I have the uncomfortable
feeling that others are making a religion out of it, as if the
conceptual problems of programming could be solved by a simple
trick, by a simple form of coding discipline! 

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Keeping a list of records with named fields that can be updated

2022-12-15 Thread songbird
Peter Otten wrote:
>
> While I think what you need is a database instead of the collection of
> csv files the way to alter namedtuples is to create  a new one:

  the files are coming from the web site that stores the
accounts.  i already have manually created files from many
years ago with some of the same information but to go back
and reformat all of those would be a lot of work.  it is
much easier to just take the files as supplied and process
them if i can do that instead.

  i do know database stuff well enough but this is fairly
simple math and i'd like to avoid creating yet another
copy in yet another format to have to deal with.


> >>> from collections import namedtuple
> >>> Row = namedtuple("Row", "foo bar baz")
> >>> row = Row(1, 2, 3)
> >>> row._replace(bar=42)
> Row(foo=1, bar=42, baz=3)
>
> An alternative would be dataclasses where basic usage is just as easy:
>
> >>> from dataclasses import make_dataclass
> >>> Row = make_dataclass("Row", "foo bar baz".split())
> >>> row = Row(1, 2, 3)
> >>> row
> Row(foo=1, bar=2, baz=3)
> >>> row.bar = 42
> >>> row
> Row(foo=1, bar=42, baz=3)

  thanks, i'll give these a try.  :)


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


RE: Single line if statement with a continue

2022-12-15 Thread avi.e.gross
Multiple returns is not always a problem as it depends on the nature of a
task whether it has complex enough cases. 

I have seen code that instead sets Boolean variables when it is ready to
return and everything else keeps checking the variables to skip further
processing so the program then slides down to a single return statement. If
done properly, it boils down to the same result if VERY carefully done but
with lots of sometimes complex IF statements that may be not be updated well
if the logic changes a bit.

In such cases, I vastly prefer clean and unambiguous returns  from the
function right at the point where the decision is made, UNLESS the exit is
not always clean as there may be cleanup or finalization of some kind
required that is best done at a single point.

If efficiency is an issue, then clearly a rapid exit may beat one where
processing continues for a while and also often beats a method that involves
creating and calling multiple smaller functions with lots of overhead.

Having said all that, of course, if you can find a fairly simple algorithm
that only returns from one place, use it instead of a convoluted one. The
issue is not necessarily that multiple return points are bad, but that they
are often a symptom of sloppy planning. But for some problems, they fit well
and simplify things.

-Original Message-
From: Python-list  On
Behalf Of Stefan Ram
Sent: Thursday, December 15, 2022 7:42 AM
To: python-list@python.org
Subject: Re: Single line if statement with a continue

Chris Green  writes:
>I always try to avoid multiple returns from functions/methods, as soon 
>as things get complex it's all to easy to miss clean-up etc.

  This "complexity" could also mean that the function has
  become too large. In such a case, one could say that the
  /size/ of the function is the actual cause of problems
  and not multiple returns.

|Fools ignore complexity. Pragmatists suffer it. Some can avoid it. 
|Geniuses remove it.
Alan Perlis (1922/1990)

  Within a small function, multiple returns are rarely
  a problem.

  When a function is large, one can apply well-known
  refactors. For an example, look at the code in the
  first post of the thread

Python script not letting go of files
Date: Tue, 29 Nov 2022 12:52:15 +

  and then at my reply of

29 Nov 2022 14:44:39 GMT.

>"No multiple returns" is often found in programming guidelines.

  I religiously followed that when I did more C programming
  than today. Then, I read an article about how the result
  pattern makes functions measurably slower. (It should not
  with an optimizing compiler, but it did due to those
  measurements. Can't find that article now, though.)

  "Result pattern" I call writing,

if a:
result = 123
else:
result = 456
return result

  , instead of,

if a:
return 123
else
return 456 

  .


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

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


Re: sqlite3 double quote behavior

2022-12-15 Thread John K. Parejko
Thanks for the discussion. I’m aware that SQLite has several different options 
for identifier quoting, but they’re not cross-compatible with other SQL, 
whereas double quotes are (modulo this strange SQLite behavior).

Is anyone here familiar with the python sqlite3 implementation? I wonder how 
hard it would be to raise up the `sqlite3_db_config` generically, or have a 
specific function to set just the DQS_DDL and DQS_DML settings? It looks like 
everything interesting is in `Modules/_sqlite/module.c`, but I’m not familiar 
with the cpython internals.

John

> On 13Dec 2022, at 13:58, Chris Angelico  wrote:
> 
> On Wed, 14 Dec 2022 at 08:19, Roel Schroeven  wrote:
>> 
>> Chris Angelico schreef op 13/12/2022 om 20:01:
>>> On Wed, 14 Dec 2022 at 06:00, Roel Schroeven  wrote:
 
 Stefan Ram schreef op 13/12/2022 om 8:42:
> "John K. Parejko"  writes:
>> I was just burned by this, where some tests I’d written
>> against an sqlite database did not fail in the way that they
>> “should” have, because of this double-quoted string issue.
> 
>   In standard SQL, double quotes denote identifiers that are
>   allowed to contain special characters.
 Or that are equal SQL keywords, which can be a reason to double-quote
 them. SQL engines sometimes add new keywords; explicitly marking string
 literals as string literals prevents future conflicts and confusion.
 
 Perhaps it's a better idea to use [identifier] or `identifier` instead
 though (I just learned about those on
 https://sqlite.org/lang_keywords.html). Both are not standard SQL ([] is
 used in MS Access and SQL Server, `` is used in MySQL) but both work in
 SQLite. That should prevent any ambiguity and confusion, if it doesn't
 bother you too much that it's not standard SQL.
 
>>> 
>>> Why not just use "identifier" which is standard SQL?
>> 
>> If you accidentally type [identifire] or `identifire`, SQLite will
>> produce an unknown identifier error, alerting you immediately to your typo.
>> If you accidentally type "identifire", SQLite will silently treat it as
>> a string literal instead of an identifier, causing more difficult to
>> diagnose problems.
>> 
> 
> Okay, so. exactly the same as if you use standard double quotes,
> but change the configuration option. So the options are: make
> everything worse for everyone by exacerbating the problem of
> non-standard identifier quoting, or get this API so SQLite can be
> configured, like the OP actually asked for.
> 
> Yeah. Let's not do the wrong thing.
> 
> ChrisA
> -- 
> https://mail.python.org/mailman/listinfo/python-list

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


Re: Single line if statement with a continue

2022-12-15 Thread Weatherby,Gerard
I once saw a C function full of GOTOs which jumped to the return state at the 
bottom of the functions because the programmer had learned that “multiple 
returns are a bad idea.”

I totally agree multiple returns causing confusion is a symptom of poor design, 
not a cause.

Required cleanup is easily handled by the try / finally construct.

From: Python-list  on 
behalf of avi.e.gr...@gmail.com 
Date: Thursday, December 15, 2022 at 2:07 PM
To: python-list@python.org 
Subject: RE: Single line if statement with a continue
*** Attention: This is an external email. Use caution responding, opening 
attachments or clicking on links. ***

Multiple returns is not always a problem as it depends on the nature of a
task whether it has complex enough cases.

I have seen code that instead sets Boolean variables when it is ready to
return and everything else keeps checking the variables to skip further
processing so the program then slides down to a single return statement. If
done properly, it boils down to the same result if VERY carefully done but
with lots of sometimes complex IF statements that may be not be updated well
if the logic changes a bit.

In such cases, I vastly prefer clean and unambiguous returns  from the
function right at the point where the decision is made, UNLESS the exit is
not always clean as there may be cleanup or finalization of some kind
required that is best done at a single point.

If efficiency is an issue, then clearly a rapid exit may beat one where
processing continues for a while and also often beats a method that involves
creating and calling multiple smaller functions with lots of overhead.

Having said all that, of course, if you can find a fairly simple algorithm
that only returns from one place, use it instead of a convoluted one. The
issue is not necessarily that multiple return points are bad, but that they
are often a symptom of sloppy planning. But for some problems, they fit well
and simplify things.

-Original Message-
From: Python-list  On
Behalf Of Stefan Ram
Sent: Thursday, December 15, 2022 7:42 AM
To: python-list@python.org
Subject: Re: Single line if statement with a continue

Chris Green  writes:
>I always try to avoid multiple returns from functions/methods, as soon
>as things get complex it's all to easy to miss clean-up etc.

  This "complexity" could also mean that the function has
  become too large. In such a case, one could say that the
  /size/ of the function is the actual cause of problems
  and not multiple returns.

|Fools ignore complexity. Pragmatists suffer it. Some can avoid it.
|Geniuses remove it.
Alan Perlis (1922/1990)

  Within a small function, multiple returns are rarely
  a problem.

  When a function is large, one can apply well-known
  refactors. For an example, look at the code in the
  first post of the thread

Python script not letting go of files
Date: Tue, 29 Nov 2022 12:52:15 +

  and then at my reply of

29 Nov 2022 14:44:39 GMT.

>"No multiple returns" is often found in programming guidelines.

  I religiously followed that when I did more C programming
  than today. Then, I read an article about how the result
  pattern makes functions measurably slower. (It should not
  with an optimizing compiler, but it did due to those
  measurements. Can't find that article now, though.)

  "Result pattern" I call writing,

if a:
result = 123
else:
result = 456
return result

  , instead of,

if a:
return 123
else
return 456

  .


--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!lVeLOl91qPUjowC1ch_u353upn8X-V4rsReaNberWpIXBlBP6CYcDgr_aaMb0ZHoYX4YWO8id1biCn6sW7V6vJM$

--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!lVeLOl91qPUjowC1ch_u353upn8X-V4rsReaNberWpIXBlBP6CYcDgr_aaMb0ZHoYX4YWO8id1biCn6sW7V6vJM$
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Subtracting dates to get hours and minutes

2022-12-15 Thread MRAB

On 2022-12-15 18:14, Gronicus@SGA.Ninja wrote:

So far so good , I can now use a variable in datetime.datetime but it only
works if I hard-code the time/date information. Now I want to have the code
read from a file but I get: TypeError: function takes at most 9 arguments
(26 given)

I figure that the structure in the file is incorrect. What should it be? The
entry in the file is (2022, 12, 13,  5,  3, 30) but when my program tries to
use it I get the error.

The program is a bit more sophisticated now but here is the update with a
sample of the SPECIFICATIONS.txt file:
=

# This program compares two Timedate values, subtracts the two and
# converts the difference to seconds and hours.
#

#  %A Monday#  %a Mon   #  %B January   #  %b Jan
#  %d 05 day#  %m month as 01   #  %Y 2020  #  %y 20
#  %H 24#  %I 12#  %M 30 min#  %S Seconds

import time
import datetime
from time import gmtime, strftime ##define strftime as time/date right now
# ==

def GetSpecByItem(GetThisOne):  #get line by item in column 4 - 7
 ItemValue = "--"
 
 with open("SPECIFICATIONS.txt" , 'r') as infile:

  for lineEQN in infile: # loop to find each line in the file for that
dose
 if ((lineEQN[4:7]== GetThisOne)):


You don't need the parentheses, and certainly 2 pairs of them!


ItemValue = lineEQN[30:60].strip()   # Just the Data
 return(ItemValue)


You're returning a _string_.

I suggest using 'literal_eval' from the 'ast' module to convert the 
string safely into a tuple.


However, if the 'for' loop fails to match a line, the function will 
return "--", which won't be of any use later on unless you check for it 
specifically and, say, report an error to the user.




"""
SPECIFICATIONS.txt

IYf HRB Humalog R Date   (2018, 12, 4, 10,  7, 00)   ##
IYf HRG Humulin R Date   (2022, 12, 13,  5,  3, 30)  ##
"""
# == Main() ==
print()
Startt = "404"
Stopp  = "404"

Answer = "Y"
Answer = input("Run test A? (" + Answer + ")" )

if Answer == "Y" or Answer == "y" or Answer == "":
print()
print(" Running Test A:")
#   Year  Mth Day Hour Min Sec
Startt  =   2018, 12, 4, 10,  7, 00
Stopp   =   2022, 12, 12, 1, 15, 30
NowTime =   2022, 12, 14, 21, 15, 30


'Startt' and 'Stopp' here are tuples.


else:
print(" Running Test B:")
Startt = GetSpecByItem("HRG")
Stopp =  GetSpecByItem("HRB")


'Startt' and 'Stopp' here are _strings_.


NowTime = strftime("(%Y, %m, %d, %H, %M, %S)")

print()

print("55NowTime = " + str(NowTime))
print("56 Startt = " + str(Startt))
print("57  Stopp = " + str(Stopp))
print()

NowTime =  datetime.datetime(*NowTime)
Startt =   datetime.datetime(*Startt)
Stopp =datetime.datetime(*Stopp)

These will work if 'Startt' and 'Stopp' are tuples, but not if they're 
strings. In the latter case, you're effectively passing multiple 
single-characters strings into 'datetime'.



#Start == Startt  # True"
#print("Startt test = " + Start)
# =
print()
c = NowTime - Stopp
minutes = c.total_seconds() / 60
minutes = c.seconds / 60
hours = 0

while (minutes > 59):
 minutes = minutes - 60
 hours += 1
minutes = round(minutes)
print ("77 Hours = <" + str(hours) + ">")
print ("78 Minutes =   <" + str(minutes) + ">")
if hours > 7:
 print(" Time to inject Humulin R u500.")

pause = input("Pause")
# ==

-Original Message-
From: Python-list  On
Behalf Of Thomas Passin
Sent: Tuesday, December 13, 2022 11:20 PM
To: python-list@python.org
Subject: Re: Subtracting dates to get hours and minutes

Your problem is that datetime.datetime does not accept a tuple as an
argument.  It expects an integer value for the first argument, but you
supplied a tuple.  In Python, you can use a sequence (e.g., tuple or
list) the way you want by prefixing it with an asterisk.  This causes the
sequence of items to be treated as individual arguments. So:

Startt = datetime.datetime(2022, 12, 13,  5,  3, 30)
st1 = (2022, 12, 13,  5,  3, 30)
dts1 = datetime.datetime(*st1)  # NOT datetime.datetime(st1)
dts1 == Startt  # True

On 12/13/2022 10:43 PM, Gronicus@SGA.Ninja wrote:

  As is, Test A works.
  Comment out Test A and uncomment Test B it fails.
  In Test B, I move the data into a variable resulting with the report:
 "TypeError: an integer is required (got type tuple)

How do I fix this?

#-

import datetime
#=
# Test A   Hard coded Date/Time
Startt = datetime.datetime(2022, 12, 13,  5,  3, 30) Stopp =  
datetime.datetime(2022, 12, 12, 21, 15, 30)

Re: Single line if statement with a continue

2022-12-15 Thread MRAB

On 2022-12-15 19:05, avi.e.gr...@gmail.com wrote:

Multiple returns is not always a problem as it depends on the nature of a
task whether it has complex enough cases.

I have seen code that instead sets Boolean variables when it is ready to
return and everything else keeps checking the variables to skip further
processing so the program then slides down to a single return statement. If
done properly, it boils down to the same result if VERY carefully done but
with lots of sometimes complex IF statements that may be not be updated well
if the logic changes a bit.

In such cases, I vastly prefer clean and unambiguous returns  from the
function right at the point where the decision is made, UNLESS the exit is
not always clean as there may be cleanup or finalization of some kind
required that is best done at a single point.

A problem with having a single return is that it can lead to excessive 
indentation:


if test_1:
...

if test_2:
...

if test_3:
...

return

With multiple returns, however:

if not test_1:
return

...

if not test_2:
return

...

if not test_3:
return

...

return


If efficiency is an issue, then clearly a rapid exit may beat one where
processing continues for a while and also often beats a method that involves
creating and calling multiple smaller functions with lots of overhead.

Having said all that, of course, if you can find a fairly simple algorithm
that only returns from one place, use it instead of a convoluted one. The
issue is not necessarily that multiple return points are bad, but that they
are often a symptom of sloppy planning. But for some problems, they fit well
and simplify things.

-Original Message-
From: Python-list  On
Behalf Of Stefan Ram
Sent: Thursday, December 15, 2022 7:42 AM
To: python-list@python.org
Subject: Re: Single line if statement with a continue

Chris Green  writes:
I always try to avoid multiple returns from functions/methods, as soon 
as things get complex it's all to easy to miss clean-up etc.


   This "complexity" could also mean that the function has
   become too large. In such a case, one could say that the
   /size/ of the function is the actual cause of problems
   and not multiple returns.

|Fools ignore complexity. Pragmatists suffer it. Some can avoid it.
|Geniuses remove it.
Alan Perlis (1922/1990)

   Within a small function, multiple returns are rarely
   a problem.

   When a function is large, one can apply well-known
   refactors. For an example, look at the code in the
   first post of the thread

Python script not letting go of files
Date: Tue, 29 Nov 2022 12:52:15 +

   and then at my reply of

29 Nov 2022 14:44:39 GMT.


"No multiple returns" is often found in programming guidelines.


   I religiously followed that when I did more C programming
   than today. Then, I read an article about how the result
   pattern makes functions measurably slower. (It should not
   with an optimizing compiler, but it did due to those
   measurements. Can't find that article now, though.)

   "Result pattern" I call writing,

if a:
 result = 123
else:
 result = 456
return result

   , instead of,

if a:
 return 123
else
 return 456

   .


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



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


Re: Subtracting dates to get hours and minutes

2022-12-15 Thread Thomas Passin
It's hard to be sure from what you have offered, but I suspect that you 
are taking the string "(2022, 12, 13,  5,  3, 30)" from the file and 
using it as is.  When you feed that in as a starred argument, the string 
gets treated as a sequence where each item is a character in the string. 
 Your example contains 26 characters, which matches the error message, 
so that's probably what is going on.


You need to convert the string into the correct integers, because is the 
datetime function expects to get integers, not strings.  It isn't going 
to work with a string that looks like a tuple when it is printed.


Here is one way you could do this.  From the input file, extract the 
string. Call it dstr.  Then you have to get rid of the parentheses and 
separate out each item so you can convert it into an integer.  So:


items = dstr[1:-2].split(',')  # This creates a list of strings.
# print(items) --> ['2022', ' 12', ' 13', '  5', '  3', ' 3']

# Create a tuple of integers from the string items
seq = (int(n) for n in items)
# or make it a list instead: seq = [int(n) for n in items]

# And here is the datetime object you wanted
d1 = datetime.datetime(*seq)


On 12/15/2022 1:14 PM, Gronicus@SGA.Ninja wrote:

So far so good , I can now use a variable in datetime.datetime but it only
works if I hard-code the time/date information. Now I want to have the code
read from a file but I get: TypeError: function takes at most 9 arguments
(26 given)

I figure that the structure in the file is incorrect. What should it be? The
entry in the file is (2022, 12, 13,  5,  3, 30) but when my program tries to
use it I get the error.

The program is a bit more sophisticated now but here is the update with a
sample of the SPECIFICATIONS.txt file:
=

# This program compares two Timedate values, subtracts the two and
# converts the difference to seconds and hours.
#

#  %A Monday#  %a Mon   #  %B January   #  %b Jan
#  %d 05 day#  %m month as 01   #  %Y 2020  #  %y 20
#  %H 24#  %I 12#  %M 30 min#  %S Seconds

import time
import datetime
from time import gmtime, strftime ##define strftime as time/date right now
# ==

def GetSpecByItem(GetThisOne):  #get line by item in column 4 - 7
 ItemValue = "--"
 
 with open("SPECIFICATIONS.txt" , 'r') as infile:

  for lineEQN in infile: # loop to find each line in the file for that
dose
 if ((lineEQN[4:7]== GetThisOne)):
ItemValue = lineEQN[30:60].strip()   # Just the Data
 return(ItemValue)

"""
SPECIFICATIONS.txt

IYf HRB Humalog R Date   (2018, 12, 4, 10,  7, 00)   ##
IYf HRG Humulin R Date   (2022, 12, 13,  5,  3, 30)  ##
"""
# == Main() ==
print()
Startt = "404"
Stopp  = "404"

Answer = "Y"
Answer = input("Run test A? (" + Answer + ")" )

if Answer == "Y" or Answer == "y" or Answer == "":
print()
print(" Running Test A:")
#   Year  Mth Day Hour Min Sec
Startt  =   2018, 12, 4, 10,  7, 00
Stopp   =   2022, 12, 12, 1, 15, 30
NowTime =   2022, 12, 14, 21, 15, 30
else:
print(" Running Test B:")
Startt = GetSpecByItem("HRG")
Stopp =  GetSpecByItem("HRB")
NowTime = strftime("(%Y, %m, %d, %H, %M, %S)")

print()

print("55NowTime = " + str(NowTime))
print("56 Startt = " + str(Startt))
print("57  Stopp = " + str(Stopp))
print()

NowTime =  datetime.datetime(*NowTime)
Startt =   datetime.datetime(*Startt)
Stopp =datetime.datetime(*Stopp)

#Start == Startt  # True"
#print("Startt test = " + Start)
# =
print()
c = NowTime - Stopp
minutes = c.total_seconds() / 60
minutes = c.seconds / 60
hours = 0

while (minutes > 59):
 minutes = minutes - 60
 hours += 1
minutes = round(minutes)
print ("77 Hours = <" + str(hours) + ">")
print ("78 Minutes =   <" + str(minutes) + ">")
if hours > 7:
 print(" Time to inject Humulin R u500.")

pause = input("Pause")
# ==


-Original Message-
From: Python-list  On
Behalf Of Thomas Passin
Sent: Tuesday, December 13, 2022 11:20 PM
To: python-list@python.org
Subject: Re: Subtracting dates to get hours and minutes

Your problem is that datetime.datetime does not accept a tuple as an
argument.  It expects an integer value for the first argument, but you
supplied a tuple.  In Python, you can use a sequence (e.g., tuple or
list) the way you want by prefixing it with an asterisk.  This causes the
sequence of items to be treated as individual arguments. So:

Startt = datetime.datetime(2022, 12, 13,  5,  3, 30)
st1 = (2022, 12, 13,  5,  3, 30)
dts1 = datetime.datetime(*st1)  # NOT datetime.datetime(st1)
dts1 == Startt  # True

On 12/13/2022 10:43 PM, Gronicus@SGA.Ninja wrote:

   As is, Test A w

Re: sqlite3 double quote behavior

2022-12-15 Thread Thomas Passin
There is a Python adapter for SQLITE called "APSW".  It has a config() 
function.  I looked in the codebase and it defines the two configuration 
constants needed to turn off the double quote behavior (see 
https://sqlite.org/quirks.html).  These constants are 
SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.


This makes me think that the double-quote behavior can be turned off by 
Python code, though I haven't tried it.


From the APSW docs (see 
https://rogerbinns.github.io/apsw/tips.html#about-python-apsw-and-sqlite-versions):


"APSW wraps the SQLite C API. That means when SQLite adds new constant 
or API, then so does APSW. You can think of APSW as the Python 
expression of SQLite’s C API. You can lookup SQLite APIs to find which 
APSW functions and attributes call them."


On 12/15/2022 2:18 PM, John K. Parejko wrote:

Thanks for the discussion. I’m aware that SQLite has several different options 
for identifier quoting, but they’re not cross-compatible with other SQL, 
whereas double quotes are (modulo this strange SQLite behavior).

Is anyone here familiar with the python sqlite3 implementation? I wonder how 
hard it would be to raise up the `sqlite3_db_config` generically, or have a 
specific function to set just the DQS_DDL and DQS_DML settings? It looks like 
everything interesting is in `Modules/_sqlite/module.c`, but I’m not familiar 
with the cpython internals.

John


On 13Dec 2022, at 13:58, Chris Angelico  wrote:

On Wed, 14 Dec 2022 at 08:19, Roel Schroeven  wrote:


Chris Angelico schreef op 13/12/2022 om 20:01:

On Wed, 14 Dec 2022 at 06:00, Roel Schroeven  wrote:


Stefan Ram schreef op 13/12/2022 om 8:42:

"John K. Parejko"  writes:

I was just burned by this, where some tests I’d written
against an sqlite database did not fail in the way that they
“should” have, because of this double-quoted string issue.


   In standard SQL, double quotes denote identifiers that are
   allowed to contain special characters.

Or that are equal SQL keywords, which can be a reason to double-quote
them. SQL engines sometimes add new keywords; explicitly marking string
literals as string literals prevents future conflicts and confusion.

Perhaps it's a better idea to use [identifier] or `identifier` instead
though (I just learned about those on
https://sqlite.org/lang_keywords.html). Both are not standard SQL ([] is
used in MS Access and SQL Server, `` is used in MySQL) but both work in
SQLite. That should prevent any ambiguity and confusion, if it doesn't
bother you too much that it's not standard SQL.



Why not just use "identifier" which is standard SQL?


If you accidentally type [identifire] or `identifire`, SQLite will
produce an unknown identifier error, alerting you immediately to your typo.
If you accidentally type "identifire", SQLite will silently treat it as
a string literal instead of an identifier, causing more difficult to
diagnose problems.



Okay, so. exactly the same as if you use standard double quotes,
but change the configuration option. So the options are: make
everything worse for everyone by exacerbating the problem of
non-standard identifier quoting, or get this API so SQLite can be
configured, like the OP actually asked for.

Yeah. Let's not do the wrong thing.

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




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


Re: Single line if statement with a continue

2022-12-15 Thread Thomas Passin

On 12/15/2022 3:58 AM, Chris Green wrote:

Thomas Passin  wrote:

I personally tend to use

if test: return

even inside larger blocks.


I always try to avoid multiple returns from functions/methods, as soon
as things get complex it's all to easy to miss clean-up etc.

"No multiple returns" is often found in programming guidelines.


Yes, or alternatively, "If any branch uses a return, they all should."


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


Re: Single line if statement with a continue

2022-12-15 Thread Grant Edwards
On 2022-12-15, MRAB  wrote:

> A problem with having a single return is that it can lead to excessive 
> indentation:
>
>  if test_1:
>  ...
>
>  if test_2:
>  ...
>
>  if test_3:
>  ...
>
>  return

I sometimes have to work on code like that with bocks nested 8-10
levels deep spread out over hundreds of lines. The first thing I do is
convert it to something like the code below. Check for error
conditions up front and exit accordingly.

When working in C, a "goto error" or "goto done" instead of "return"
can provide a "single return" if that's deemed important.

>
> With multiple returns, however:
>
>  if not test_1:
>  return
>
>  ...
>
>  if not test_2:
>  return
>
>  ...
>
>  if not test_3:
>  return
>
>  ...
>
>  return

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


RE: Subtracting dates to get hours and minutes

2022-12-15 Thread Gronicus
Yes, it works like a charm. On the tupility of it all.
Special thanks for the explanation too…..

 

Now that the code no longer produces the errors, I see that the year and month 
not included in the calculation? How do I fix this?

 

From: anthony.flury  
Sent: Thursday, December 15, 2022 1:47 PM
To: Gronicus@SGA.Ninja
Subject: RE: Subtracting dates to get hours and minutes

 

What is likely happening is that when you read the data from the file you are 
not reading a tuple, you are reading a 26 charcter string.

You have to convert that string into a tuple - the easiest way will be somthing 
like this : 

 

timet = tuple(int(x.strip()) for x in timestring[1:-1].split(','))

 

where timestring is the data you get from the file

The [1:-1] removes the () from the data

The .split(",") method creates a temporary list from the remaining string 
breaking the string where there are commas

The x.strip() removes spaces from each item in the temporary list.

 

Note that the * unpack operator doesn't just unpack tuples, it works on an 
iterable, so when you read the data from the file currently, and then use * on 
it, it will pass 26 separate characters to the function.

 



-- Original Message --
From: Gronicus@SGA.Ninja  
To: "'Thomas Passin'" mailto:li...@tompassin.net> >; 
python-list@python.org  
Sent: Thursday, 15 Dec, 22 At 18:14
Subject: RE: Subtracting dates to get hours and minutes

So far so good , I can now use a variable in datetime.datetime but it only
works if I hard-code the time/date information. Now I want to have the code
read from a file but I get: TypeError: function takes at most 9 arguments
(26 given)

I figure that the structure in the file is incorrect. What should it be? The
entry in the file is (2022, 12, 13, 5, 3, 30) but when my program tries to
use it I get the error.

The program is a bit more sophisticated now but here is the update with a
sample of the SPECIFICATIONS.txt file:
=

# This program compares two Timedate values, subtracts the two and
# converts the difference to seconds and hours.
#

# %A Monday # %a Mon # %B January # %b Jan
# %d 05 day # %m month as 01 # %Y 2020 # %y 20
# %H 24 # %I 12 # %M 30 min # %S Seconds

import time
import datetime
from time import gmtime, strftime ##define strftime as time/date right now
# ==

def GetSpecByItem(GetThisOne): #get line by item in column 4 - 7
ItemValue = "--"

with open("SPECIFICATIONS.txt" , 'r') as infile:
for lineEQN in infile: # loop to find each line in the file for that
dose
if ((lineEQN[4:7]== GetThisOne)):
ItemValue = lineEQN[30:60].strip() # Just the Data
return(ItemValue)

"""
SPECIFICATIONS.txt

IYf HRB Humalog R Date (2018, 12, 4, 10, 7, 00) ##
IYf HRG Humulin R Date (2022, 12, 13, 5, 3, 30) ##
"""
# == Main() ==
print()
Startt = "404"
Stopp = "404"

Answer = "Y"
Answer = input("Run test A? (" + Answer + ")" )

if Answer == "Y" or Answer == "y" or Answer == "":
print()
print(" Running Test A:")
# Year Mth Day Hour Min Sec
Startt = 2018, 12, 4, 10, 7, 00 
Stopp = 2022, 12, 12, 1, 15, 30
NowTime = 2022, 12, 14, 21, 15, 30
else:
print(" Running Test B:")
Startt = GetSpecByItem("HRG")
Stopp = GetSpecByItem("HRB")
NowTime = strftime("(%Y, %m, %d, %H, %M, %S)")

print()
print("55 NowTime = " + str(NowTime))
print("56 Startt = " + str(Startt))
print("57 Stopp = " + str(Stopp))
print()

NowTime = datetime.datetime(*NowTime)
Startt = datetime.datetime(*Startt)
Stopp = datetime.datetime(*Stopp)

#Start == Startt # True" 
#print("Startt test = " + Start)
# =
print()
c = NowTime - Stopp 
minutes = c.total_seconds() / 60 
minutes = c.seconds / 60
hours = 0

while (minutes > 59):
minutes = minutes - 60
hours += 1
minutes = round(minutes)
print ("77 Hours = <" + str(hours) + ">")
print ("78 Minutes = <" + str(minutes) + ">")
if hours > 7:
print(" Time to inject Humulin R u500.")

pause = input("Pause") 
# ==


-Original Message-
From: Python-list mailto:python-list-bounces+gronicus=sga.ni...@python.org> > On
Behalf Of Thomas Passin
Sent: Tuesday, December 13, 2022 11:20 PM
To: python-list@python.org  
Subject: Re: Subtracting dates to get hours and minutes

Your problem is that datetime.datetime does not accept a tuple as an
argument. It expects an integer value for the first argument, but you
supplied a tuple. In Python, you can use a sequence (e.g., tuple or
list) the way you want by prefixing it with an asterisk. This causes the
sequence of items to be treated as individual arguments. So:

Startt = datetime.datetime(2022, 12, 13, 5, 3, 30)
st1 = (2022, 12, 13, 5, 3, 30)
dts1 = datetime.datetime(*st1) # NOT datetime.datetime(st1)
dts1 == Startt # T

Re: Subtracting dates to get hours and minutes

2022-12-15 Thread Weatherby,Gerard



Not sure what you mean:

x = datetime.datetime(year=2018,month=12,day=4,hour=10)
y = datetime.datetime(year=2022,month=12,day=13,hour=5)
print(x -y)


-1470 days, 5:00:00

If you want to display years, (x-y).days /365

From: Python-list  on 
behalf of Gronicus@SGA.Ninja 
Date: Thursday, December 15, 2022 at 5:02 PM
To: 'anthony.flury' , python-list@python.org 

Subject: RE: Subtracting dates to get hours and minutes
*** Attention: This is an external email. Use caution responding, opening 
attachments or clicking on links. ***

Yes, it works like a charm. On the tupility of it all.
Special thanks for the explanation too…..



Now that the code no longer produces the errors, I see that the year and month 
not included in the calculation? How do I fix this?



From: anthony.flury 
Sent: Thursday, December 15, 2022 1:47 PM
To: Gronicus@SGA.Ninja
Subject: RE: Subtracting dates to get hours and minutes



What is likely happening is that when you read the data from the file you are 
not reading a tuple, you are reading a 26 charcter string.

You have to convert that string into a tuple - the easiest way will be somthing 
like this :



timet = tuple(int(x.strip()) for x in timestring[1:-1].split(','))



where timestring is the data you get from the file

The [1:-1] removes the () from the data

The .split(",") method creates a temporary list from the remaining string 
breaking the string where there are commas

The x.strip() removes spaces from each item in the temporary list.



Note that the * unpack operator doesn't just unpack tuples, it works on an 
iterable, so when you read the data from the file currently, and then use * on 
it, it will pass 26 separate characters to the function.





-- Original Message --
From: Gronicus@SGA.Ninja 
To: "'Thomas Passin'" mailto:li...@tompassin.net> >; 
python-list@python.org 
Sent: Thursday, 15 Dec, 22 At 18:14
Subject: RE: Subtracting dates to get hours and minutes

So far so good , I can now use a variable in datetime.datetime but it only
works if I hard-code the time/date information. Now I want to have the code
read from a file but I get: TypeError: function takes at most 9 arguments
(26 given)

I figure that the structure in the file is incorrect. What should it be? The
entry in the file is (2022, 12, 13, 5, 3, 30) but when my program tries to
use it I get the error.

The program is a bit more sophisticated now but here is the update with a
sample of the SPECIFICATIONS.txt file:
=

# This program compares two Timedate values, subtracts the two and
# converts the difference to seconds and hours.
#

# %A Monday # %a Mon # %B January # %b Jan
# %d 05 day # %m month as 01 # %Y 2020 # %y 20
# %H 24 # %I 12 # %M 30 min # %S Seconds

import time
import datetime
from time import gmtime, strftime ##define strftime as time/date right now
# ==

def GetSpecByItem(GetThisOne): #get line by item in column 4 - 7
ItemValue = "--"

with open("SPECIFICATIONS.txt" , 'r') as infile:
for lineEQN in infile: # loop to find each line in the file for that
dose
if ((lineEQN[4:7]== GetThisOne)):
ItemValue = lineEQN[30:60].strip() # Just the Data
return(ItemValue)

"""
SPECIFICATIONS.txt

IYf HRB Humalog R Date (2018, 12, 4, 10, 7, 00) ##
IYf HRG Humulin R Date (2022, 12, 13, 5, 3, 30) ##
"""
# == Main() ==
print()
Startt = "404"
Stopp = "404"

Answer = "Y"
Answer = input("Run test A? (" + Answer + ")" )

if Answer == "Y" or Answer == "y" or Answer == "":
print()
print(" Running Test A:")
# Year Mth Day Hour Min Sec
Startt = 2018, 12, 4, 10, 7, 00
Stopp = 2022, 12, 12, 1, 15, 30
NowTime = 2022, 12, 14, 21, 15, 30
else:
print(" Running Test B:")
Startt = GetSpecByItem("HRG")
Stopp = GetSpecByItem("HRB")
NowTime = strftime("(%Y, %m, %d, %H, %M, %S)")

print()
print("55 NowTime = " + str(NowTime))
print("56 Startt = " + str(Startt))
print("57 Stopp = " + str(Stopp))
print()

NowTime = datetime.datetime(*NowTime)
Startt = datetime.datetime(*Startt)
Stopp = datetime.datetime(*Stopp)

#Start == Startt # True"
#print("Startt test = " + Start)
# =
print()
c = NowTime - Stopp
minutes = c.total_seconds() / 60
minutes = c.seconds / 60
hours = 0

while (minutes > 59):
minutes = minutes - 60
hours += 1
minutes = round(minutes)
print ("77 Hours = <" + str(hours) + ">")
print ("78 Minutes = <" + str(minutes) + ">")
if hours > 7:
print(" Time to inject Humulin R u500.")

pause = input("Pause")
# ==


-Original Message-
From: Python-list mailto:python-list-bounces+gronicus=sga.ni...@python.org> > On
Behalf Of Thomas Passin
Sent: Tuesday, December 13, 2022 11:20 PM
To: python-list@python.org 
Subject: Re: Subtracting dates to get h

RE: Subtracting dates to get hours and minutes

2022-12-15 Thread Gronicus
Yes, it works like a charm. On the tupility of it all.
Special thanks for the explanation too…..

 

(Originally asked but I found the errors. All is working)

Now that the code no longer produces the errors, I see that the year and month 
not included in the calculation? How do I fix this?

 

From: anthony.flury  
Sent: Thursday, December 15, 2022 1:47 PM
To: Gronicus@SGA.Ninja
Subject: RE: Subtracting dates to get hours and minutes

 

What is likely happening is that when you read the data from the file you are 
not reading a tuple, you are reading a 26 charcter string.

You have to convert that string into a tuple - the easiest way will be somthing 
like this : 

 

timet = tuple(int(x.strip()) for x in timestring[1:-1].split(','))

 

where timestring is the data you get from the file

The [1:-1] removes the () from the data

The .split(",") method creates a temporary list from the remaining string 
breaking the string where there are commas

The x.strip() removes spaces from each item in the temporary list.

 

Note that the * unpack operator doesn't just unpack tuples, it works on an 
iterable, so when you read the data from the file currently, and then use * on 
it, it will pass 26 separate characters to the function.

 



-- Original Message --
From: Gronicus@SGA.Ninja  
To: "'Thomas Passin'" mailto:li...@tompassin.net> >; 
python-list@python.org  
Sent: Thursday, 15 Dec, 22 At 18:14
Subject: RE: Subtracting dates to get hours and minutes

So far so good , I can now use a variable in datetime.datetime but it only
works if I hard-code the time/date information. Now I want to have the code
read from a file but I get: TypeError: function takes at most 9 arguments
(26 given)

I figure that the structure in the file is incorrect. What should it be? The
entry in the file is (2022, 12, 13, 5, 3, 30) but when my program tries to
use it I get the error.

The program is a bit more sophisticated now but here is the update with a
sample of the SPECIFICATIONS.txt file:
=

# This program compares two Timedate values, subtracts the two and
# converts the difference to seconds and hours.
#

# %A Monday # %a Mon # %B January # %b Jan
# %d 05 day # %m month as 01 # %Y 2020 # %y 20
# %H 24 # %I 12 # %M 30 min # %S Seconds

import time
import datetime
from time import gmtime, strftime ##define strftime as time/date right now
# ==

def GetSpecByItem(GetThisOne): #get line by item in column 4 - 7
ItemValue = "--"

with open("SPECIFICATIONS.txt" , 'r') as infile:
for lineEQN in infile: # loop to find each line in the file for that
dose
if ((lineEQN[4:7]== GetThisOne)):
ItemValue = lineEQN[30:60].strip() # Just the Data
return(ItemValue)

"""
SPECIFICATIONS.txt

IYf HRB Humalog R Date (2018, 12, 4, 10, 7, 00) ##
IYf HRG Humulin R Date (2022, 12, 13, 5, 3, 30) ##
"""
# == Main() ==
print()
Startt = "404"
Stopp = "404"

Answer = "Y"
Answer = input("Run test A? (" + Answer + ")" )

if Answer == "Y" or Answer == "y" or Answer == "":
print()
print(" Running Test A:")
# Year Mth Day Hour Min Sec
Startt = 2018, 12, 4, 10, 7, 00 
Stopp = 2022, 12, 12, 1, 15, 30
NowTime = 2022, 12, 14, 21, 15, 30
else:
print(" Running Test B:")
Startt = GetSpecByItem("HRG")
Stopp = GetSpecByItem("HRB")
NowTime = strftime("(%Y, %m, %d, %H, %M, %S)")

print()
print("55 NowTime = " + str(NowTime))
print("56 Startt = " + str(Startt))
print("57 Stopp = " + str(Stopp))
print()

NowTime = datetime.datetime(*NowTime)
Startt = datetime.datetime(*Startt)
Stopp = datetime.datetime(*Stopp)

#Start == Startt # True" 
#print("Startt test = " + Start)
# =
print()
c = NowTime - Stopp 
minutes = c.total_seconds() / 60 
minutes = c.seconds / 60
hours = 0

while (minutes > 59):
minutes = minutes - 60
hours += 1
minutes = round(minutes)
print ("77 Hours = <" + str(hours) + ">")
print ("78 Minutes = <" + str(minutes) + ">")
if hours > 7:
print(" Time to inject Humulin R u500.")

pause = input("Pause") 
# ==


-Original Message-
From: Python-list mailto:python-list-bounces+gronicus=sga.ni...@python.org> > On
Behalf Of Thomas Passin
Sent: Tuesday, December 13, 2022 11:20 PM
To: python-list@python.org  
Subject: Re: Subtracting dates to get hours and minutes

Your problem is that datetime.datetime does not accept a tuple as an
argument. It expects an integer value for the first argument, but you
supplied a tuple. In Python, you can use a sequence (e.g., tuple or
list) the way you want by prefixing it with an asterisk. This causes the
sequence of items to be treated as individual arguments. So:

Startt = datetime.datetime(2022, 12, 13, 5, 3, 30)
st1 = (2022, 12, 13, 5, 3, 30)
dts1 = datetime.dat

Re: Subtracting dates to get hours and minutes

2022-12-15 Thread Thomas Passin

Oops,

"items = dstr[1:-2].split(',')"

should have read

"items = dstr[1:-1].split(',')".

On 12/15/2022 1:56 PM, Thomas Passin wrote:
It's hard to be sure from what you have offered, but I suspect that you 
are taking the string "(2022, 12, 13,  5,  3, 30)" from the file and 
using it as is.  When you feed that in as a starred argument, the string 
gets treated as a sequence where each item is a character in the string. 
  Your example contains 26 characters, which matches the error message, 
so that's probably what is going on.


You need to convert the string into the correct integers, because is the 
datetime function expects to get integers, not strings.  It isn't going 
to work with a string that looks like a tuple when it is printed.


Here is one way you could do this.  From the input file, extract the 
string. Call it dstr.  Then you have to get rid of the parentheses and 
separate out each item so you can convert it into an integer.  So:


items = dstr[1:-2].split(',')  # This creates a list of strings.
# print(items) --> ['2022', ' 12', ' 13', '  5', '  3', ' 3']

# Create a tuple of integers from the string items
seq = (int(n) for n in items)
# or make it a list instead: seq = [int(n) for n in items]

# And here is the datetime object you wanted
d1 = datetime.datetime(*seq)


On 12/15/2022 1:14 PM, Gronicus@SGA.Ninja wrote:
So far so good , I can now use a variable in datetime.datetime but it 
only
works if I hard-code the time/date information. Now I want to have the 
code

read from a file but I get: TypeError: function takes at most 9 arguments
(26 given)

I figure that the structure in the file is incorrect. What should it 
be? The
entry in the file is (2022, 12, 13,  5,  3, 30) but when my program 
tries to

use it I get the error.

The program is a bit more sophisticated now but here is the update with a
sample of the SPECIFICATIONS.txt file:
=

# This program compares two Timedate values, subtracts the two and
# converts the difference to seconds and hours.
#

#  %A Monday    #  %a Mon   #  %B January   #  %b Jan
#  %d 05 day    #  %m month as 01   #  %Y 2020  #  %y 20
#  %H 24    #  %I 12    #  %M 30 min    #  %S Seconds

import time
import datetime
from time import gmtime, strftime ##define strftime as time/date right 
now

# ==

def GetSpecByItem(GetThisOne):  #get line by item in column 4 - 7
 ItemValue = "--"
 with open("SPECIFICATIONS.txt" , 'r') as infile:
  for lineEQN in infile: # loop to find each line in the file for 
that

dose
 if ((lineEQN[4:7]== GetThisOne)):
    ItemValue = lineEQN[30:60].strip()   # Just the Data
 return(ItemValue)

"""
SPECIFICATIONS.txt

IYf HRB Humalog R Date   (2018, 12, 4, 10,  7, 00)   ##
IYf HRG Humulin R Date   (2022, 12, 13,  5,  3, 30)  ##
"""
# == Main() ==
print()
Startt = "404"
Stopp  = "404"

Answer = "Y"
Answer = input("Run test A? (" + Answer + ")" )

if Answer == "Y" or Answer == "y" or Answer == "":
    print()
    print(" Running Test A:")
#   Year  Mth Day Hour Min Sec
    Startt  =   2018, 12, 4, 10,  7, 00
    Stopp   =   2022, 12, 12, 1, 15, 30
    NowTime =   2022, 12, 14, 21, 15, 30
else:
    print(" Running Test B:")
    Startt = GetSpecByItem("HRG")
    Stopp =  GetSpecByItem("HRB")
    NowTime = strftime("(%Y, %m, %d, %H, %M, %S)")
print()
print("55    NowTime = " + str(NowTime))
print("56 Startt = " + str(Startt))
print("57  Stopp = " + str(Stopp))
print()

NowTime =  datetime.datetime(*NowTime)
Startt =   datetime.datetime(*Startt)
Stopp =    datetime.datetime(*Stopp)

#Start == Startt  # True"
#print("Startt test = " + Start)
# =
print()
c = NowTime - Stopp
minutes = c.total_seconds() / 60
minutes = c.seconds / 60
hours = 0

while (minutes > 59):
 minutes = minutes - 60
 hours += 1
minutes = round(minutes)
print ("77 Hours = <" + str(hours) + ">")
print ("78 Minutes =   <" + str(minutes) + ">")
if hours > 7:
 print(" Time to inject Humulin R u500.")

pause = input("Pause")
# ==


-Original Message-
From: Python-list  On
Behalf Of Thomas Passin
Sent: Tuesday, December 13, 2022 11:20 PM
To: python-list@python.org
Subject: Re: Subtracting dates to get hours and minutes

Your problem is that datetime.datetime does not accept a tuple as an
argument.  It expects an integer value for the first argument, but you
supplied a tuple.  In Python, you can use a sequence (e.g., tuple or
list) the way you want by prefixing it with an asterisk.  This causes the
sequence of items to be treated as individual arguments. So:

Startt = datetime.datetime(2022, 12, 13,  5,  3, 30)
st1 = (2022, 12, 13,  5,  3, 30)
dts1 = datetime.date

Re: Subtracting dates to get hours and minutes

2022-12-15 Thread MRAB

On 2022-12-15 22:49, Gronicus@SGA.Ninja wrote:

Yes, it works like a charm. On the tupility of it all.
Special thanks for the explanation too…..

  


(Originally asked but I found the errors. All is working)

Now that the code no longer produces the errors, I see that the year and month 
not included in the calculation? How do I fix this?

  
How long is a month? How many months are there until January 1? On 
December 25, many months will there be until January 1? And how many 
years are there until January 1?


[snip]

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


Re: Subtracting dates to get hours and minutes

2022-12-15 Thread Thomas Passin

On 12/15/2022 11:34 PM, MRAB wrote:

On 2022-12-15 22:49, Gronicus@SGA.Ninja wrote:

Yes, it works like a charm. On the tupility of it all.
Special thanks for the explanation too…..


(Originally asked but I found the errors. All is working)

Now that the code no longer produces the errors, I see that the year 
and month not included in the calculation? How do I fix this?


First you should read about the function you are using.  In this case, 
it is at


https://docs.python.org/3.10/library/datetime.html

I found this page using an internet search for "python datetime.datetime".

All Python functions, classes, and methods will normally be found in the 
documentation for the standard library, as this one is.


You should also look at datetime.timedelta, as various people have 
posted here.  Try to understand what is being described.  Then try to 
make simple examples that will show if you can get what you want, or if 
not, what more information you need.  Look through the rest of the 
documentation of (in this case) the datetime module and see if any of 
the other functionality looks like it will produce what you want.


It is important to understand clearly what your input data is like, and 
what results you need to achieve.  If you are not clear, or do not 
express yourself clearly, it will be hard and frustrating for others on 
the list to assist you.


For example, you wrote "I see that the year and month not included in 
the calculation".  I don't know what you mean.  You already include the 
month in the tuple that you feed to datetime.datetime().  That is, in 
the input string you showed, "(2022, 12, 13,  5,  3, 30)", it seems that 
"2022" represents a year, "12" represents a month, "13" represents a day 
of the month, and so forth.


So I don't understand how year and month not included.  I see that you 
do think that something is not coming out right, but you need to be more 
precise about what you mean so that others can understand too.


To succeed at programming, you need to be very precise about attending 
to details because the computer cannot know what you have in your mind. 
To succeed at getting help, you have to be precise and accurate about 
what you want to achieve and what is not coming out right, and describe 
those things simply and clearly to other people.


In other words, please help us to help you.
--
https://mail.python.org/mailman/listinfo/python-list