I have little python code to work with date and time and I need to ask question to modify the script. The script is provided below,
from datetime import date, datetime, timedelta
import random
def perdelta(start, end, delta):
curr = start
while curr < end:
yield curr
curr += delta
s = datetime.now() - timedelta(days=10)
e = datetime.now() - timedelta(days=8)
# start = 2017-10-01 06:44:00.480208
# end = 2017-10-03 06:44:00.480583
# print "\n"
# print "start = ", s
# print "end = ", e
# print "\n"
dates = []
for result in perdelta(s, e, timedelta(seconds=15)):
print result
As I print out the result, I get the values like
2017-10-03 06:49:50.009049
2017-10-03 06:50:05.009049
How do I keep to the 3 digits after the decimal like 2017-10-03 06:49:50.349?
If you’re just interested in the string keeping only the first 3 digits in the microseconds, you can just use string splicing.
for result in perdelta(s, e, timedelta(seconds=15)):
print (str(result)[:-3])
A better method which is what ShadowRanger mentioned in the comments, that uses .isoformat(...) to format directly to ISO 8601 with an additional milliseconds time spec. But unfortunately the timespec argument was only recently added in Python 3.6.
Related
I'm doing a delete operation of 3000 elements from a binary search tree of size 6000 ( sorted therefore one sided tree). I need to calculate the time taken for completing all the deletes
I did this
bst2 = foo.BinarySearchTree() #init
insert_all_to_tree(bst2,insert_lines) #insert 6000 elements
start = datetime.now() #start time
for idx, line in enumerate(lines):
bst2.delete(line) #deleting
if (idx%10 == 0):
print("deleted ", (idx+1), "th element - ", line)
end = datetime.now() #completion time
duration = end - start
print(duration.microseconds) #duration in microseconds
I got the answer 761716 microseconds which is less than even a minute when my actual code ran for about 5 hours. I expected something in the ranges of 10^9 - 10^10. I even checked the max integer allowed in python to see if it's related to that but apparently that's not the problem.
Why I'm I getting a wrong answer for the duration?
datetime.now() returns a datetime, so doing math with it doesn't work out. You want to either use time.time() (Python < v3.3), time.perf_counter() (Python v3.3 until v3.7) or time.perf_counter_ns() (Python > v3.7).
time.time() and time.perf_counter() both return float, and time.perf_counter_ns() returns int.
I am trying to make a clock that stops at a certain time. This is the code I currently have:
import time as t
import datetime as dt
import os
tc = input("When do you want this to stop? (military time please) ")
exit = False
date = str(dt.datetime.now().date())
while (exit == False):
if dt.datetime.now() == date + " " + tc + ":00.0000":
exit = True
else:
print(dt.datetime.now())
t.sleep(0.01)
os.system('cls')
The problem is that the time never exactly gets to the perfect place for the parts less than a second so how do I get it to stop?
do you mean like this?
if dt.datetime.now() >= date + " " + tc + ":00.0000"
also please format the datetime.now() to the string you want
using something like datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
You could check if the time has passed, something like
if dt.datetime.now() >= date + " " + tc + ":00.0000":
You'll probably have to fiddle with the available methods to get it to work, I don't know if there's a built in comparator in that library. But something along those lines just checking if the current time is past the desired time.
I have a path files which are named by time (201803061500) etc. What I need is a time conversion, because I use while loop to open a few of them there is an error when I want files from for example (...1555 to ... 1615) and Python sees an obivous problem because after 1555 is 1560, but I want him to convert that to time so after (...1555 will be ... 1600) any ideas how to use it?
Btw. Time conversion must be contain 4 digits, so it cannot be 16:00/16-00 etc. it must be 1600, because it goes as an input to my pathfile. Any ideas?
UPDATE - I did this, but this code is rubbish and I think my problem might be solved by one command.
Start_time_hours = input('Enter start time (hh): ' )
Start_time_minutes = input('Enter start time (mm): ')
if Start_time_hours >= 24:
print ("Values from 00 to 23 only!")
if Start_time_minutes >= 60:
x = Start_time_hours + 1
y = Start_time_minutes - Start_time_minutes
if y == 0:
print "Ok"
print x, y
if Start_time_minutes <= 55:
print Start_time_hours, Start_time_minutes
One easy way to handle unformated time is the datetime. You can first strip your strings and then do whatever you want !
from datetime import datetime, timedelta
from time import strtime
datetime_object = datetime.strptime(file_name, '%Y%m%d%H%M')
print(datetime_object) # returns '2018-03-06 15:00:00'
delta = timedelta(minutes=5)
next_time = datetime_object + delta
print(next_time) # returns '2018-03-06 15:05:00'
Finally you can get your string back by using time.strftime() function
new_string = next_time.strftime('%Y%m%d%H%M')
print(new_string) # returns '201803061505'
Source datetime: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
Source time: https://docs.python.org/2/library/time.html
Start_time_hours += (Start_time_minutes / 60)
Start_time_minutes %= 60
Start_time_minutes += 5
Those three lines solved my problem, datetime also works, but if you put those variables to input pathfile, you'll get an error. That's why I've choosen this solution.
I need to make a simple program which converts a 24 hour time which is input, into 12 hour time, which produces an error if an incorrect time is put in. I currently have the code below, however, I have a few issues. One issue is that if "0924" is input, it outputs "924 am", when I need it to produce "9:24am" (the space isn't hugely important but it's preferred). Also, I'm not entirely sure where to start for doing 0001-0059, because "0001" for example produces "1 am", which is obviously incorrect.
print("Enter a time in 24 hour time, e.g. '1620'")
time = (int(input("Time: ")))
normal = 0
if (time == 0000):
normal="12:00am"
print (normal)
elif (time>1200):
normal = (time - 1200)
print (int(normal), ("pm"))
elif (time<1200):
normal = time
print (int(normal), ("am"))
Thanks in advance for any help!
Try this
import time
timevalue_24hour = "1620";
timevalue_24hour = timevalue_24hour[:2] + ':' + timevalue_24hour[2:]
print (timevalue_24hour)
t = time.strptime(timevalue_24hour, "%H:%M")
timevalue_12hour = time.strftime( "%I:%M %p", t )
print (timevalue_12hour)
Take input as a string. Assign it to timevalue_24hour and rest will work
When printing, normal is just a number. The 0s disappear because you don't write 0s in front of numbers normally. I would suggest doing something like this
def normal_check(num):
if num < 10:
return "000"+str(num)
elif num < 100:
return "00"+str(num)
elif num < 1000:
return "0"+str(num)
else:
return str(num)
print("Enter a time in 24 hour time, e.g. '1620'")
time = (int(input("Time: ")))
normal = 0
if (time == 0000):
normal="12:00am"
print (normal)
elif (time>1200):
normal = normal_check(time - 1200)
print (normal, ("pm"))
elif (time<1200):
normal = normal_check(time)
print (normal, ("am"))
The best way to do this will be to take the input as an str rather than int. Take it in as str and split it into two int values of two digits.
Then the first string if less than 12 will be hour else subtract 12 from first str and use PM. Also, the second str will just be minutes.
No clue why this is happening. I must be missing something obvious.
I'm trying to make a counter print out something like SMPTE code (hours:minutes:seconds:frames (assuming 24fps)).
Code thus far:
import time
s_time = time.time()
def format_time():
t = time.time() - s_time
if t < 1:
print '00:00:00:%02d' % int(t/0.041666666666666664)
elif t < 60:
t = str(t).split('.')
print '00:00:%02d:%02d' % (int(t[0]), int(int(t[1][:4])/0.041666666666666664) )
while True:
format_time()
All seems well initially, until the duration surpasses 1 second and the elif branch is entered. Seconds print out fine, but the frames print out the full multi-digit result of the calculation. Given that the formatting operator is specifying %02d, just like it does in the first if branch (which behaves as expected), why is it not obeying in the second branch? I'm at a loss trying to figure out why it is still printing the full result rather than the truncated version.
You are trying to get the integer part and the fractional part of the float to print your result. It is a good practice to use operators and functions on numeric data directly instead of adding a heavy overhead by converting the float into str and back to number.
Use the math module modf function for that. It will also simplify your algorithm.
import time
import math
s_time = time.time()
def format_time():
t = time.time() - s_time
if t < 60:
f,i = math.modf(t)
print '00:00:%02d:%02d' % (i, f/0.041666666666666664)
while True:
format_time()
PS: for your code error, in your elif block, you are passing t as an integer with a huge value instead of passing the 0.xxxxx value of it. This error wouldn't occur if you keep using the math functions of floats.
I expect you want something like this:
hours = int(t)/3600
minutes = (int(t)/60)%60
seconds = int(t)%60
frames = (t-int(t))*24
print '%02d:%02d:%02d:%02d' % (hours, minutes, seconds, frames)
%02d means: print the integer and if it's shorter than 2 digits, prefix it with zeroes.
it doesn't limit the formatted string to two digits.
edit: one way of getting the first 2 (rounded) digits of a number n would be:
n = 13900
print round(n/10**math.floor(math.log10(n)-1))
or if you don't care about rounding, just cut the string...