Comparing Time - Python [duplicate] - python

This question already has answers here:
How do I check the difference, in seconds, between two dates?
(7 answers)
Closed 4 years ago.
I have a function where I read the time from a file. I put this into a variable. I then subtract this value from the current time which most of the time will give me a value around .
My problem is im not sure how to check if this value which I attach to a variable is greater than say 20 seconds.
def numberchecker():
with open('timelog.txt', 'r') as myfile:
data=myfile.read().replace('\n','')
a = datetime.strptime(data,'%Y-%m-%d %H:%M:%S.%f')
b = datetime.now()
c = b-a (This outputs for example: 0:00:16.657538)
d = (would like this to a number I set for example 25 seconds)
if c > d:
print ("blah blah")

The difference which you're getting is a timedelta object.
You can just use c.seconds to get the seconds.

if c.total_seconds() > datetime.timedelta(seconds=d):
print ("blah blah")

Related

Acessing a random array a given number of times without using the random module (Python) [duplicate]

This question already has answers here:
Shuffle an array with python, randomize array item order with python
(11 answers)
How can I randomly select an item from a list?
(17 answers)
Closed 2 years ago.
For instance, let's say I have a random array [5,2,1,3,6,4] and I want to access it at least 6 times (i.e. 6 == len(array)) (the acess order doesn't matter, nor does it matter that I've accessed them all). How can I randomly access the whole array without popping any of the values ?
In other words, I am trying to write a function find_new_index which takes an index i such that:
arr = [5,2,1,3,6,4]
i=0
x = 0
while i < 6:
access = arr[i]
x+=1
i = i + find_new_index(i)
assert(x >= 6)
The idea is that this function works for any random array of size N which has random values from 1 to N.
PS : The easy way to write find_indexis to generate a random number within it. However, I want to know if it's possible to write this function without loops or any function calls.
This differs from other questions, since I don't want to use the Random Module.
You can use the random.choice(my_list) function.
import random
arr = [5,2,1,3,6,4]
i = 0
while i < 6:
access = random.choice(arr)
#do whatever you want
i += 1
For example, print the access adding a print(access) instead of the comment can output something like:
2
2
6
6
4
1
you probably want to use the random module:
import random
arr=[5,2,1,3,6,4]
access =[]
for i in range(len(arr)):
access.append(arr[random.randint(0,len(arr))])
print(access)
>>> [1,2,1,4,4,6]
UPDATE
This differs from other questions, since I don't want to use the Random Module.
the one way i think you can make it is with the time module....
from datetime import datetime
def get_random(mini,maxi):
timestamp = datetime.now().timestamp() * 1000
return timestamp % maxi + mini
# rest of the code ...
for i in range(len(arr)):
access.append(arr[get_random(0,len(arr))])

Variable inside python format specifier [duplicate]

This question already has an answer here:
How to pad numbers with variable substitution for padding width in format or f string? [duplicate]
(1 answer)
Closed 7 months ago.
I am wondering whether I can add a variable inside the f string to specify the width of item to be printed.
For example:
print("{:>5}".format("cat"))
In the example how can I replace 5 with a variable that can change at runtime.
inside the f string
Be careful using the term "f string" -- you're talking about a format string whereas an f-string is a feature of the latest releases of Python and something different, but related:
animal = 'cat'
pad = 5
print(f"{animal:>{pad}}")
Otherwise, if you just want a format string without the f-string, then #JohnnyMopp's comment (+1) shows the correct syntax.
Here is how:
a = 5
print("{:>"f"{a}""}".format("cat"))
Output:
cat
You can also do that using str.rjust():
a = 5
print("cat".rjust(a))
Output:
cat

Leave empty spaces with format while printing an String in python [duplicate]

This question already has answers here:
How to print a string at a fixed width?
(7 answers)
Closed 2 years ago.
I have created a program.Here I need to leave some space and print an String after the spaces.I did that program with format in python.my code is below,
name = "myname"
print("{0:>10}".format(name))
#output=" myname"
Here, the sum of empty spaces and the length of name is equals to 10.I have declared the size inside print.
But I need to declare the size as a variable.I tried it like this,
num = 10
name = "myname"
print("{0:>num}".format(name))
but it did not worked.I need to know how I can fix this.I need to take the same output with giving the size with an variable.please help...
Try this one:
num_of_spaces = 10
name = "myname"
name.rjust(num_of_spaces)
Try:
num = 10
name ="myname"
print(" "*num,name)
Or you can also do it via:
name ="myname"
print('{0} {1}'.format(' '*num,name))

Capped at 32-bit maximum, why is my code not able to pull the solution above this maximum? [duplicate]

This question already has answers here:
Numpy is calculating wrong [duplicate]
(2 answers)
Closed 3 years ago.
I am attempting to solve problem 8 of projecteuler. I am having difficulty understanding exactly why my code is not outputting the correct solution. I am aware that the solution to this problem is above the 32 bit maximum, but I do not know how to allow python to work with numbers above that within my code.
For reference, the original question states : "Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?"
from numpy import prod
f = 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
z = list(int(i) for i in str(f))
a1 =[]
start = 0
end = start + 13
while end <= len(z):
a1.append(prod(z[start:end]))
start+=1
end+=1
a = a1.index(max(a1))
print(a1[a]) #prints the product solution
print('---')
dimlen=end-start
newstart = a
newend=a+dimlen
print(z[newstart:newend]) #prints the integers that build the solution
I keep getting the number 2091059712, (the solution is 23514624000)
I think it might be numpy.prod. It might be preserving the input type and wrapping the value. Try using:
def prod(it):
p = 1
for m in it:
p *= m
return p

Converting minutes to HH:MM format in Python [duplicate]

This question already has answers here:
How get hours:minutes
(4 answers)
Closed 9 years ago.
First of all, I'd like to point out that I'm a beginner with Python.
My problem is that I can't figure out what is the proper way to convert minutes to HH:MM format in Python.
Any help is appreciated!
Use the divmod() function:
'{:02d}:{:02d}'.format(*divmod(minutes, 60))
Here divmod() divides the minutes by 60, returning the number of hours and the remainder, in one.
Demo:
>>> minutes = 135
>>> '{:02d}:{:02d}'.format(*divmod(minutes, 60))
'02:15'

Categories