I am doing some project for myself and i am stuck with an assignment.
I have strict time that's 30min
I have a user that gives an input like: 24008
I need to convert an user input to time(2min:40sec:08milisec) and substract it from main time.
I tried time.strftime('%M:%S:%f', 1800) to show main Time (30min) like 30:00:00 but i don't seem to get the datetime or time imports and how do they work. Same with user input.
Can anyone with a kind heart would guide me to a right path on how to get this logic done and by what function?
I can't share a code because i don't have any working logic for this one.
A datetime.time object would probably be the best data structure to use for this
Your initial value of 30 minutes would be defined like this
import datetime
strict_time = datetime.time(minutes=30)
If the user input you gave as an example will always be the input format then it becomes a little hard to parse as python's datetime module's strptime behaviour does not handle 2-digit millisecond inputs and 1 digit minute inputs. If the input format is exactly the same (5 digits with 1 minute digit, 2 second digits and 2 millisecond digits) then the following would work
user_input = '24008'
input_time = datetime.timedelta(
minutes=int(user_input[0]),
seconds=int(user_input[1:2]),
microseconds=int(user_input[3:4])
)
new_time = strict_time - input_time
Related
If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?
This is what I have tried:
>>> import datetime
>>> t=datetime.time(6,52)
>>> print (t)
06:52:00
>>> b=t+datetime.timedelta (8 hours,15 minutes)
File "<stdin>", line 1
b=t+datetime.timedelta (8 hours,15 minutes)
^
SyntaxError: invalid syntax
````````````````````````````````````````````````````
So let's walk it back a few steps. When you tried b=t+datetime.timedelta (8 hours,15 minutes), what you were trying to do was increment your time object by 8 minutes and 15 seconds, using the timedelta function. In Python, functions take arguments, and timedelta, like any other function, has specific kinds of values you can pass for arguments. You can find them here, because since datetime is a library, it has nice documentation for everything. It looks like you were using IDLE which also gives you a peek at type hints:
So now we know that timedelta takes any one of days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0.
In our case, we want to add 8 minutes and 15 seconds to our original datetime object.
That would mean setting minutes=8 and seconds=15.
So when we call the timedelta function, to avoid that syntax error, we want to invoke the function like such:
b=t+datetime.timedelta(minutes=8, seconds=15)
And there you have it! Just remember what is and is not valid syntax in Python. Python doesn't know a thing about what you mean when you give it plain English.
I am looking to create an if then statement that involves the current time of the day. For example I want something like if it is past 2pm then do this function.
I have tried using the time module but I can't seem to find a way to get just the time of day without the extra stuff like the date. Any help?
Here is a start, and I think it'll be enough for you to get to the answer and use it how you need.
import time
print(time.strftime("%Y-%m-%d %H:%M"))
print(time.strftime("I can format the date and time in many ways. Time is: %H:%M"))
Output (when I ran it):
2017-06-21 10:40
I can format the date and time in many ways. Time is: 10:40
I have to convert date and time returned by ls of rsync into Unix epoch time float as returned by time.time().
For me here at this moment it looks like:
2017/05/24 hh:mm:ss.
But as far as I know it can vary from machine to machine as rsync uses ssh and native ls, I expect through it.
Is there any easy way to universally convert most common human readable date and time back to the Unix time float?
To be clear. I want to be able to convert any textual representation of D and T into the float.
If datetime can do this I cannot find how at the moment.
You need to use time.strptime first and then calendar.timegm
there are different options depending if you want to convert to local time or UTC time. Have a look to the documentation for that.
To get the float part, you need to input hours, minutes, seconds and milliseconds. In your example, you give only the year, month and day, so the rest is supposed to be zero i.e. no milliseconds thus no float part.
Here a minimal example:
import calendar, time
t = time.strptime('2017/05/24', '%Y/%m/%d')
epoch = calendar.timegm(time.struct_time(t))
print(epoch)
1495584000
I have a datetime.timedelta time object in python (e.g. 00:02:00) I want to check if this time is less than 5 minutess and greater then 1 minute.
I'm not sure how to construct a timedelta object and I'm also not sure if this is the right format to compare times. Would anyone know the most efficient way to do this?
So if you start with a string that's rigorously and precisely in the format 'HH:MM:SS', timedelta doesn't directly offer a string-parsing function, but it's not hard to make one:
import datetime
def parsedelta(hhmmss):
h, m, s = hhmmss.split(':')
return datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s))
If you need to parse many different variants you'll be better off looking for third-party packages like dateutil.
Once you do have timedelta instance, the check you request is easy, e.g:
onemin = datetime.timedelta(minutes=1)
fivemin = datetime.timedelta(minutes=5)
if onemin < parsedelta('00:02:00') < fivemin:
print('yep')
will, as expected, display yep.
I want to generate a fixed-length (say 10 characters) hash based on current date & time. This hash will be append to names of the uploaded files from my users. How can I do that in Python?
Batteries included:
Python3
import hashlib
import time
hashlib.sha1().update(str(time.time()).encode("utf-8"))
print(hashlib.sha1().hexdigest())
print(hashlib.sha1().hexdigest()[:10])
Python2
import hashlib
import time
hash = hashlib.sha1()
hash.update(str(time.time()))
print hash.hexdigest()
print hash.hexdigest()[:10]
I think my comment is a reasonable answer so I am going to post it. The code uses the python time() function to get the number of seconds since the unix epoch:
import time
import datetime
ts = int(time.time()) # this removes the decimals
# convert the timestamp to a datetime object if you want to extract the date
d = datetime.datetime.fromtimestamp(ts)
The time stamp is currently a 10 digit integer that can easily be converted back to a datetime object for other uses. If you want to further shrink the length of the timestamp you could encode the number in hexadecimal or some other format. ie.
hex(int(time.time()))
This reduces the length to 8 characters if you remove the 0x prefix
EDIT:
In your comment you specified that you don't want people to figure out the original date so I would suggest doing something like:
hex(int(time.time() + 12345))[2:] #The [2:] removes the 0x prefix
Just chose a number and remember to subtract it when you are trying to extract the timestamp. Without knowing this number the user would have a very difficult time inferring the real date from your code.
int(stamp,16) - 12345
import time
'{0:010x}'.format(int(time.time() * 256))[:10]
Check out strftime for python. You can format the date/time string any number of ways to get the 'look' you want.
What about changing the base of current milliseconds since epoch. For example, in JavaScript, changing to base 36:
Date.now().toString(36)
Results in :
"jv8pvlbg"
That should be a safe hash, up to milliseconds, respect date order and smaller than 10.
The only thing is that is not safe, but in your case security is not important right?
Sorry I don't have the answer for python, but it should by straightforward and should nor require any library. My two cents.