Python how to get current time as an integer - python

This is my code that I tried to use but it doesn't work since it's a string
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M")
print("time=", current_time)
wake_up=0
x=current_time - wake_up - 0.40
wake_up = float(input("when are you gonna wake up"))
print(x)
I am trying to make a calculator where as it prints the current time. (for example 23:00) and then the input asks what time are you going to wake up and you write (for example 08:30) and the output should be "You will get 09:30 hours and minutes of sleep" or preferably "You will get 9 hours and 30 minutes of sleep"
I tried to do this but it is a string and cannot be calculated and I tried to find an integer version of the now.strftime module. Can someone help me find out how to do this?

You'll need to use datetime.strptime(), which takes in a date string and a format string (reference here) and converts the string to a datetime object.
In your case, you would use the following to convert wake_up to a datetime object:
dt = datetime.strptime(wake_up, "%H:%M")

Modifications done based on your code:
from datetime import datetime, date
now_time = datetime.now().time() # get time only
current_time_str = now.strftime("%H:%M")
print("time=", current_time_str)
#wake_up = input("when are you gonna wake up")
wake_up = '08:30' # assuming this is user input
wake_up_time = datetime.strptime(wake_up, "%H:%M").time()
x = datetime.combine(date.today(), wake_up_time) - datetime.combine(date.today(), now_time)
print(str(x)) #also, you can get hours by x.seconds/3600
Other questions will help you.
Python speed testing - Time Difference - milliseconds
Converting string into datetime
subtract two times in python
Format timedelta to string

Related

How to parse and calculate the elapsed seconds in a date stamp with this format?

Given a string like this:
2020-04-09T13:15:52.838Z - 2020-04-09T13:16:09.704Z
What is the correct way to calculate the amount of elapsed seconds? So far I tried this:
s = '2021-03-09T13:15:52.838Z - 2021-03-09T13:16:09.704Z'.split(' - ')
datetime.strptime(s[0], "%Y-%m-%d").date() - datetime.strptime(s[1],"%Y-%m-%d").date()
However, I am not sure how to extract the seconds and calculate the elapsed time between the two time stamps. Any idea of how to get the elapsed time in seconds?
Basically, you want to convert each string into a datetime (here using datetime.strptime() and using a format string that matches the format of your time strings) and then subtract one from the other to get a datetime.timedelta object. Then you can call the total_seconds() method on the timedelta object. Here's one way you might do it:
import datetime
s = '2021-03-09T13:15:52.838Z - 2021-03-09T13:16:09.704Z'.split(' - ')
first_time = datetime.datetime.strptime(s[0], '%Y-%m-%dT%H:%M:%S.%fZ')
second_time = datetime.datetime.strptime(s[1], '%Y-%m-%dT%H:%M:%S.%fZ')
time_delta = second_time - first_time
print(time_delta.total_seconds())

How to define a difference in time in seconds between a timestamp saved as a string and a current UTC timestamp

I am testing the difference between an actual UTC time and timestamp when my object was saved in a table (UTC). It must be not more than 60 seconds.
Example of timestamp_from_table (string from my site): 2021-02-05 13:51:52
After researching for options to make this, I came to this approach:
timestamp_from_table = driver.find_element_by_css_selector("my_locator").text
current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime()) # current time converted to string
current_time_truncated = datetime.strptime(current_time, "%Y-%m-%d %H:%M:%S") # cutting milliseconds
date_time_obj = datetime.strptime(timestamp_from_table, '%Y-%m-%d %H:%M:%S') # converting string timestamp to a datetime object
time_difference = current_time_truncated - date_time_obj
result = time_difference.seconds # datetime.timedelta represented in seconds
assert result in range(1, 60), error()
It works just fine, but probably there is a shorter way to compare a difference between a timestamp saved as string and actual utc timestamp. Thanks for any advice.
I'm reading between the lines a bit, but it sounds like at a high level your goal is to calculate the elapsed seconds between two times. If I'm right about that, here is a typical way to do it in Python:
import datetime
import time
previous = datetime.datetime.now()
time.sleep(5) # Added to simulate the passing of time for demonstration purposes
current = datetime.datetime.now()
elapsed_seconds = (current - previous) / datetime.timedelta(seconds=1)
"Division" by timedelta is the key to getting elapsed seconds (or any other time unit) between two datetime objects. While not UTC specific hopefully this shines a light on an approach that works for you.

How to add a certain time to a datetime?

I want to add hours to a datetime and use:
date = date_object + datetime.timedelta(hours=6)
Now I want to add a time:
time='-7:00' (string) plus 4 hours.
I tried hours=time+4 but this doesn't work. I think I have to int the string like int(time) but this doesn't work either.
Better you parse your time like below and access datetime attributes for getting time components from the parsed datetime object
input_time = datetime.strptime(yourtimestring,'yourtimeformat')
input_seconds = input_time.second # for seconds
input_minutes = input_time.minute # for minutes
input_hours = input_time.hour # for hours
# Usage: input_time = datetime.strptime("07:00","%M:%S")
Rest you have datetime.timedelta method to compose the duration.
new_time = initial_datetime + datetime.timedelta(hours=input_hours,minutes=input_minutes,seconds=input_seconds)
See docs strptime
and datetime format
You need to convert to a datetime object in order to add timedelta to your current time, then return it back to just the time portion.
Using date.today() just uses the arbitrary current date and sets the time to the time you supply. This allows you to add over days and reset the clock to 00:00.
dt.time() prints out the result you were looking for.
from datetime import date, datetime, time, timedelta
dt = datetime.combine(date.today(), time(7, 00)) + timedelta(hours=4)
print dt.time()
Edit:
To get from a string time='7:00' to what you could split on the colon and then reference each.
this_time = this_time.split(':') # make it a list split at :
this_hour = this_time[0]
this_min = this_time[1]
Edit 2:
To put it all back together then:
from datetime import date, datetime, time, timedelta
this_time = '7:00'
this_time = this_time.split(':') # make it a list split at :
this_hour = int(this_time[0])
this_min = int(this_time[1])
dt = datetime.combine(date.today(), time(this_hour, this_min)) + timedelta(hours=4)
print dt.time()
If you already have a full date to use, as mentioned in the comments, you should convert it to a datetime using strptime. I think another answer walks through how to use it so I'm not going to put an example.

Rounding off date time now

Hi people I am new to python. I'm developing a port scanner and need the start time and the time it took to complete the scan. I have manged to do this, however I want the time format as 12.58.32 when I use the time.datetimenow() I get the milli seconds printed. I dont want this. Can anyone help please? I know how to get the time taken to scan. t1 - t2 = scanTime. I just want it rounded of to seconds.
You can try like this. This will give you only current time without microsecond in string format.
import datetime
datetime.datetime.now().strftime("%H.%M.%S")
If you want to convert this string in datetime object then you can also try like this and then extract time as your wish.
datetime.datetime.strptime(datetime.datetime.now().strftime("%Y-%m-%d %H.%M.%S"), "%Y-%m-%d %H.%M.%S")
Write generic function to get current time:
from datetime import datetime
def get_current_time():
""" Current time"""
time_format = "%H.%M.%S"
time = datetime.now().strftime(time_format)
return datetime.strptime(time, time_format)
Now calculate t1 and t2 as per your need:
t1 = get_current_time()
t2 = get_current_time()
# Get time difference
scan_time = t2 - t1
# Convert time into seconds
total_seconds = scan_time.total_seconds()
Hope it will help.

How do you setup simple timer between two times when the other time is the next day?

Python noob here
from datetime import datetime, time
now = datetime.now()
now_time = now.time()
if now_time >= time(10,30) and now_time <= time(13,30):
print "yes, within the interval"
I would like the timer to work between 10,30 AM today and 10 AM the next day. Changing time(13,30) to time(10,00) will not work, because I need to tell python 10,00 is the next day. I should use datetime function but don't know how. Any tips or examples appreciated.
The combine method on the datetime class will help you a lot, as will the timedelta class. Here's how you would use them:
from datetime import datetime, timedelta, date, time
today = date.today()
tomorrow = today + timedelta(days=1)
interval_start = datetime.combine(today, time(10,30))
interval_end = datetime.combine(tomorrow, time(10,00))
time_to_check = datetime.now() # Or any other datetime
if interval_start <= time_to_check <= interval_end:
print "Within the interval"
Notice how I did the comparison. Python lets you "nest" comparisons like that, which is usually more succinct than writing if start <= x and x <= end.
P.S. Read https://docs.python.org/2/library/datetime.html for more details about these classes.
Consider this:
from datetime import datetime, timedelta
now = datetime.now()
today_10 = now.replace(hour=10, minute=30)
tomorrow_10 = (now + timedelta(days=1)).replace(hour=10, minute=0)
if today_10 <= now <= tomorrow_10:
print "yes, within the interval"
The logic is to create 3 datetime objects: one for today 10 AM, one for right now and one for tomorrow 10 AM. Them simply checking for the condition.
An alternative to creating time objects for the sake of comparison is to simply query the hour and minute attributes:
now= datetime.now().time()
if now.hour<10 or now.hour>10 or (now.hour==10 and now.minute>30):
print('hooray')

Categories