Taking time as input in Python - python

I mean hour and minutes. Taking them as arguments to input() function and assigning it to a variable. Is it possible?
Like this way:
time = input(current time)

In case you need hour and minutes separately
from datetime import datetime
a=datetime.now()
print(a.hour,a.minute)

intput only returns objects of type str (string).
However, you can be inventive by specifying a certain format and performing the conversion using datetime from the standard library:
from datetime import time
time = input('Enter a time in the format HH:MM \n')
# input 15:25
h, m = map(int, time.split(':'))
res = time(hour=h, minute=m)
print(res)
15:25:00

Related

what is this time format: XX:XX.X, and how to transfer it to usual year-month-day-hour-minute-second in Python

I have some date data like:
46:53.4
57:00.0
51:50.9
53:13.9
What is this time format? And how to transfer it to the usual year-month-day-hour-minute-second in Python?
Code:
import datetime
#Input Date String
t = "46:53.4"
#Return a datetime corresponding to date string
dateTimeObject = datetime.datetime.strptime(t, '%M:%S.%f')
print (dateTimeObject)
Result:
1900-01-01 00:46:53.400000
I suppose 46:53.4 means forty-six minutes and fifty-three-point-four seconds.

"PT" Formatted time string in python

I'm receiving a string which is formatted in the following way: "PTXMYS" Where X is the amount of minutes and Y is the amount of seconds.
I'd like to turn that string into an int which presents the amount of seconds in total.
I tried using datetime and other stuff and it just won't work for me, I read online that this formatting is standard for iso8601 so it's weird for me that it doesn't really work.
String example:
x="PT4M13S"
there is a third-party library that can parse these strings, isodate:
import isodate
isodate.parse_duration("PT4M13S")
# datetime.timedelta(seconds=253)
isodate.parse_duration("PT4M13S").total_seconds()
# 253.0
And for completeness, there is an option to do this with datetime's strptime and timedelta's total_seconds():
from datetime import datetime, timedelta
# parse minute and second to datetime object:
t = datetime.strptime("PT4M13S","PT%MM%SS")
# convert to timedelta to get the total seconds
td = timedelta(minutes=t.minute, seconds=t.second)
td.total_seconds()
# 253
What you are trying to do can easily be solved using regex. Try this out:
import re
m, s = re.findall('PT(\d+)M(\d+)S',x)[0]
total_secs = 60*int(m) + int(s)
print(total_secs)
Output:
253

how to get datetime to int in django? use datetime only hour and minute

I wanted to save the time as an int type so I could get the difference between the two times.
i import datetime and try to like this
now = datetime.now()
but i get this : 2017-11-18 05:47:35.262111
how to get only hour and minute to int
ex) 0547
I could not solve it.
Use the hour and minute attributes and cast them to integer.
import datetime
hour_now = int(datetime.datetime.now().hour) # for hour
minute_now = int(datetime.datetime.now().minute) # for minute
You can use .time() and slice its hour and minute part.
str(datetime.now().time())[:5].replace(':','')
# OUTPUT: '0951'
An int doesn't have leading zeros, or any other formatting
property. It is just a number. If you want to include a leading zero, I recommend using string.
Thanks to you, I could solve it.
like this
hour = datetime.now().hour
minute = datetime.now().minute
if minute >10:
return str(hour)+str(minute)
else:
return str(hour)+"0"+str(minute)

Getting Python to Print the Hour of Day

I am using the following code to get the time:
import time
time = time.asctime()
print(time)
I end up with the following result:
'Tue Feb 25 12:09:09 2014'
How can I get Python to print just the hour?
You can use datetime:
>>> import datetime as dt
>>> dt.datetime.now().hour
9
Or, rather than now() you can use today():
>>> dt.datetime.today().hour
9
Then insert into any string desired:
>>> print('The hour is {} o\'clock'.format(dt.datetime.today().hour))
The hour is 9 o'clock
Note that datetime.today() and datetime.now() are both using your computer's notion of local time zone (ie, a 'naive' datetime object).
If you want to use time zone info, it is not so trivial. You can either be on Python 3.2+ and use datetime.timezone or use the third party pytz. I am assuming your computer's timezone is fine, and a naive (non time zone datetime object) is fairly easy to use.
import time
print (time.strftime("%H"))
time.asctime() will create a string, so extracting the hours part is hard. Instead, get a proper time.struct_time object, which exposes the components directly:
t = time.localtime() # gives you an actual struct_time object
h = t.tm_hour # gives you the hour part as an integer
print(h)
You can do it in one step if that's all you need the hour for:
print(time.localtime().tm_hour)

Convert string to time format

>>> x
['00:05:09.252', '00:05:42.244', '00:06:44.546']
How can I convert these string items to 'hh:mm:ss.uuu' time format, so that I can do time calculations in this format?
I read the docs, but everything seem to be explained in context of datetime and various time zones, while I just wanna do calculation in time format without writting my own function for this task.
given your data is strictly formatted to hour:min:sec.usec
(looks like they don't have directives to deal with microseconds in python strptime, so guess you have to supply the values yourself to datetime.time's constructor)
import datetime
def timeconverter(timestring):
hour, min, sec = timestring.split(':')
sec, usec = sec.split('.')
time = datetime.time(*[int(x, 10) for x in (hour, min, sec, usec)])
return time
Check out strptime in the time module.
import time
t= time.strptime("00:05:42.244", "%H:%M:%S")
Do this if you don't care about the decimal part of the seconds. If you do care then the approuch used by thkang is a better solution.

Categories

Resources