Real Time Clock(RTC) in Python - python

I am a beginner in Python. I am wondering about does Python has Real Time Clock which is giving us exactly year, month, day, hour, min, and second?
Thank you for your help!

For Date Time operations in python you need to import datetime library.There different functions related to date formatting, getting current date and time etc.. Refer this documentation
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
Hope the above code will do your job ...

datetime.now()
Thats it.It gives the current date and time upto microseconds.
Use as you want.
Setting an alarm after 2 days.
alarm_time = date.today() + timedelta(days = 2) #set alarm time 2day after today
while(date.today()!=alarm_time): #run loop till datetoday is not alarm_time
time.sleep(60*60) #wait for an hour then recheck time
#do here anything you want to do when alarm time has reached#

you can try this:
temp.year, temp.month, temp.day,temp.hour,temp.minute,temp.second would give your desire values separately
from datetime import datetime
temp = datetime.now()
timee = "{:04d}{:02d}{:02d} {:02d}:{:02d}:{:02d}".format(temp.year, temp.month, temp.day,temp.hour,temp.minute,temp.second)

Related

How to Split a substract of a date in python

My code is the following:
date = datetime.datetime.now()- datetime.datetime.now()
print date
h, m , s = str(date).split(':')
When I print h the result is:
-1 day, 23
How do I get only the hour (the 23) from the substract using datetime?
Thanks.
If you subtract the current date from a past date, you would get a negative timedelta value.
You can get the seconds with td.seconds and corresponding hour value via just dividing by 3600.
from datetime import datetime
import time
date1 = datetime.now()
time.sleep(3)
date2 = datetime.now()
# timedelta object
td = date2 - date1
print(td.days, td.seconds // 3600, td.seconds)
# 0 0 3
You're not too far off but you should just ask your question as opposed to a question with a "real scenario" later as those are often two very different questions. That way you get an answer to your actual question.
All that said, rather than going through a lot of hoop-jumping with splitting the datetime object, assigning it to a variable which you then later use look for what you need in, it's better to just know what DateTime can do since that can be such a common part of your coding. You would also do well to look at timedelta (which is part of datetime) and if you use pandas, timestamp.
from datetime import datetime
date = datetime.now()
print(date)
print(date.hour)
I can get you the hour of datetime.datetime.now()
You could try indexing a list of a string of datetime.datetime.now():
print(list(str(datetime.datetime.now()))[11] + list(str(datetime.datetime.now()))[12])
Output (in my case when tested):
09
Hope I am of help!

Calculating time difference in python

I want to make a code in python to find out the duration an employee had worked by taking two inputs.
input1 will be the time when the employee arrived at work, in hh:mm format.
input2 will be the time when the employee left work, in hh:mm format.
I want to calculate the duration an employee worked in hh:mm format when I subtract input1 from input2.
Please help in making this code.
There is no timedelta attribute for time objects.
You can use a datetime object first, then do:
difference = datetime1 - datetime2
The, finally, do:
print(difference.strftime('%H:%M')
Alternatively, if you are only allowed to use time input/object, you can do:
import datetime
# Time in example
a = datetime.time(9, 30)
# Time out example
b = datetime.time(17, 45)
hours = abs(int(b.strftime('%H')) - int(a.strftime('%H')))
minutes = abs(int(b.strftime('%M')) - int(a.strftime('%M')))
time_difference = datetime.time(hours, minutes)
print(time_difference)

How to sleep until a specific time YYYY-MM-DD HH:MM:SS?

I have been thinking to do a sleep function where it sleeps until a certain date is called. My idea was based of date such as : 2019-01-20 12:00:00.
I haven't really figured out how to start to solve this problem. My idea was something similar such as
if there is a date given:
time.sleep(until the date and time)
So the question is how can I possibly be able to sleep until a certain time given in a value of 2019-01-20 12:00:00?
Easy, calculate how long it is, and sleep the time.
You can calculate how long it takes until your wakeup time is reached and sleep for the delta time.
Python can calculate with time intervals. If you subtract one timestamp from another, then you get a datetime.timedelta:
import datetime
import time
target = datetime.datetime(2019,1,20,12,0,0)
now = datetime.datetime.now()
delta = target - now
if delta > datetime.timedelta(0):
print('will sleep: %s' % delta)
time.sleep(delta.total_seconds())
print('just woke up')
of course, you can put that in a function:
import datetime
import time
target = datetime.datetime(2019,1,20,12,0,0)
def sleep_until(target):
now = datetime.datetime.now()
delta = target - now
if delta > datetime.timedelta(0):
time.sleep(delta.total_seconds())
return True
sleep_until(target)
You can check the return value: only if it slept, it returns True.
BTW: it's OK, to use a date in the past as target. This will generate a negative number of seconds. Sleeping a negative value will just not sleep.
if your time is a string, use this:
target = datetime.datetime.strptime('20.1.2019 20:00:00', '%d.%m.%Y %H:%M:%s')
or
target = datetime.datetime.strptime('2019-1-20 20:00:00', '%Y-%m-%d %H:%M:%s')
I did your problem in an efficient way:
import time, datetime
# given_date --> Your target time and date
dur = time.mktime(datetime.datetime.strptime(given_date, "%d-%b-%y %H:%M:%S").timetuple()) - time.time()
time.sleep(dur)
you mean something like this:
from time import sleep
from datetime import datetime
x = datetime.datetime.strptime('2019-01-20 12:00:00', '%Y-%m-%d %H:%M:%S')
y = datetime.now()
sleep((max(x,y) - min(x,y)).seconds)
You can use a while loop.
import datetime
_theday="01/01/2019"
while datetime.today() != _theday:
some stuff

Start and stop a Python script at a specific time

I am writing a script which will record the user activity in a certain period of time every day. The periods are taken from a JSON response of an API, like this:
[{"working_day": "mon", "work_start_at": "09:00", "work_end_at": "18:00"},
{"working_day": "tue", "work_start_at": "09:00", "work_end_at": "15:00"}]
Let's assume that I can parse these strings in a datetime() format.
I want to run my function accordingly to these periods and stop my function after "work_end_at". I found numerous example of how to run after certain amount of seconds, how to run every day (Python lib schedule) and examples with bash crontab. But nothing of this works for me, because all I want is to start the script at a specific time and stop at a specific time. And then, run again when the next "shift" comes.
def start():
time_periods = working_periods_table.find_all()
today = datetime.datetime.now().isoweekday()
for day in time_periods:
if day["day"] == today:
start_time = day["work_start_at"]
end_time = day["work_end_at"]
schedule.every().week.at(start_time).do(record_activity(idle_time=300))
If I've understood what you're asking, you could use while loops. Have it periodically check the current time with the times for the shift beginning and end. Below is a guide of what I mean, but I'm not sure the comparisons will work.
from time import sleep
def start():
time_periods = working_periods_table.find_all()
today = datetime.datetime.now().isoweekday()
for day in time_periods:
if day["day"] == today:
start_time = day["work_start_at"]
end_time = day["work_end_at"]
while True:
if datetime.datetime.now() >= start_time:
while True:
schedule.every().week.at(start_time).do(record_activity(idle_time=300))
if datetime.datetime.now() >= end_time:
break
break
else:
sleep(100)
I have some way to start my process at certain time but can not stop at certain time, I think you might means after running at 1 hour, even it is not finished yet, still stop the program. in this case you might can use while loop
take a look with my scripts first this might helpful
import time
from time import strftime, localtime
import datetime
now = datetime.datetime.now()
year = int(now.strftime("%Y"))
month = int(now.strftime("%m"))
day = int(now.strftime("%d"))
hour = int(now.strftime("%H"))
start_time_t = datetime.datetime(year=year, month=month, day=day, hour=22, minute=0, second=0)
waiting_time = time.mktime(start_time_t.timetuple()) - time.time()
if waiting_time >= 0:
print('the program will be start after ' + time.strftime("%H hours and %M minutes", time.gmtime(waiting_time)))
time.sleep(waiting_time)
else:
start_time_t = datetime.datetime(year=year, month=month, day=day + 1, hour=00, minute=0, second=0)
waiting_time = time.mktime(start_time_t.timetuple()) - time.time()
print('the program will be start after ' + time.strftime("%H hours and %M minutes", time.gmtime(waiting_time)))
time.sleep(waiting_time)
It will runs my program every day at 10:00 PM, if pass 10:00 PM the program will runs on the beginning of text day.
If you want to run your script at specific time intervals, I will suggest the code below which I have used on my own script. So simple to implement.
import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
# 2015 5 6 8 53 40
while True:
now = datetime.datetime.now()
if 14 <= now.hour and 23=> now.hour:
# put your code here
Note that in this piece of code I consider 2 PM until 11 PM. And more important you have to get the current hour persistently in a loop.
If you have a specific day in your mind get your current day out of the loop and compare it to your get value !! It works for me.

Python - Calculate last quarter hour of current time

How do I round the time to last quarter hour for the current time. I am able to find the last quarter hour minute, however, not able to fit this into the correct time format.
import datetime
import time
time = datetime.datetime.now()
last_quarter_minute = 15*(time.minute//15)
current_time = time.strftime("%Y/%m/%d %H:%M")
print last_quarter_minute
print current_time
Ideally, I want to be able to compare the time I get from a log, to the last quarter time.
You need to replace minute part of the time, using datetime.datetime.replace (returns a new datetime object with the specifieid field replaced):
>>> time.strftime("%Y/%m/%d %H:%M")
'2016/05/13 12:57'
>>> time.replace(minute=last_quarter_minute).strftime("%Y/%m/%d %H:%M")
'2016/05/13 12:45'
To be more precise, you need to also set second, microsecond also.

Categories

Resources