I am currently writing an Alarm Clock scipt in Python for a Raspberry Pi project. I need help with parsing the hours and minutes from both the current time and alarm time and converting them to seconds so that I can subtract current time from alarm time.
Here's an example of how to use datetime in python.
from datetime import datetime as dt
import time
format = '%Y-%m-%d %H:%M:%S'
currTime = dt.now()
alarmTime = dt.strptime('2017-12-25 08:00:00', format);
print('current time:\t', currTime)
print('alarm time:\t', alarmTime)
currTimeUnix = time.mktime(currTime.timetuple())
alarmTimeUnix = time.mktime(alarmTime.timetuple())
diff = alarmTimeUnix - currTimeUnix
print('seconds diff: \t', diff)
The output will be:
current time: 2017-12-24 22:40:30.842519
alarm time: 2017-12-25 08:00:00
seconds diff: 33570.0
Sleep example:
s = 3;
print(dt.now())
time.sleep(s)
print('I\'ve slept for', s, 'seconds')
print(dt.now())
Will result in:
2017-12-24 22:44:24.275121
I've slept for 3 seconds
2017-12-24 22:44:27.276324
Related
timestamp = f'{message.created_at}'
msg_time = datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S.%f')
now_time = datetime.now()
diff = now_time - msg_time
print('msg_time:', msg_time)
print('now_time:', now_time)
print('diff :', diff)
output :
msg_time: 2022-07-22 06:02:12.934000
now_time: 2022-07-23 01:53:52.375086
diff : 19:51:39.441086
If diff is greater than the time I specify, I want it to send a message to the channel like this:
if diff > 00:01:00.000000:
title2 = "test."
embed2 = discord.Embed(title=title2, color=0xf1c40f)
msg = await channels.send(embed=embed2)
I made it here so that if it's longer than 1 minute, it can be sent, but I don't know exactly, so it doesn't work, how can I do it?
Try using timedelta.total_seconds()
diff = diff.total_seconds()
This will convert the time difference into an integer representing the time in seconds. You can use that value much easier.
References:
https://pythontic.com/datetime/timedelta/total_seconds
https://www.geeksforgeeks.org/python-timedelta-total_seconds-method-with-example/
Quick question. Does someone know why I'am getting an 'Invalid Syntax' error usign this code? Thank you all.
def get_time_difference(date, time_string):
time_difference = datetime.now() - datetime.strptime(f"{date} {time_string}", "%d-%m-%Y %H:%M")
return f"{time_difference.hour}:{time_difference.minute}"
get_time_difference(1-1-2020 1:50)
You should call get_time_difference("1-1-2020", "1:50").
However, you will get another error:
AttributeError: 'datetime.timedelta' object has no attribute 'hour'
You can adapt get_time_difference as follows:
def get_time_difference(date, time_string):
time_difference = datetime.now() - datetime.strptime(
f"{date} {time_string}", "%d-%m-%Y %H:%M"
)
hours = time_difference.seconds // 3600
minutes = time_difference.seconds // 60 % 60
return f"{hours}:{minutes}"
from datetime import datetime
def get_time_difference(date, time_string):
time_difference = datetime.now() - datetime.strptime(f"{date} {time_string}", "%d-%m-%Y %H:%M")
return f"{time_difference.seconds // 3600}:{time_difference.seconds // 60 % 60}"
print(get_time_difference('1-1-2020', '1:50'))
Output
15:50
i want to create a program that calculate how many hours and minutes are left
for example
18:30 - 19:10 -> 0hours and 40minutes
class Uhrzeit():
def __init__(self, von, bis):
self.von = von
self.bis = bis
self.umrechnen()
def umrechnen(self):
master = 60
stunden_bis,stunden_von = int(self.bis.split(":")[0]),int(self.von.split(":")[0])
minuten_bis,minuten_von = int(self.bis.split(":")[1]),int(self.von.split(":")[1])
print stunden_bis-stunden_von, minuten_bis-minuten_von
Uhrzeit("18:30","19:10")
>> 1 -20
You could use the datetime module, which makes things quite simple.
from datetime import datetime
time1 = datetime.strptime("18:30", "%H:%M")
time2 = datetime.strptime("19:10", "%H:%M")
diff = time2 - time1
print(diff)
0:40:00
Hello!
I recently went to the LACMA museum of art, and stumbled upon this clock. Basically it uses a light sensor to determine the percent of the day that has passed. This means sunrise would be 0.00% and sunset would be 100%. I wanted to create a easier version of this, having a program Google the sunset and sunrise times for the day and work from there. Eventually this would all be transferred to a Raspberry Pi 3 (another problem for another day), therefore the code would have to be in Python. Could I maybe get some help writing it?
TLDR Version
I need a Python program that googles and returns the times of the sunset and sunrise for the day. Mind helping?
It's not pretty but it should work, just use your coordinates as the parameters.
From their website "NOTE: All times are in UTC and summer time adjustments are not included in the returned data."
import requests
from datetime import datetime
from datetime import timedelta
def get_sunrise_sunset(lat, long):
link = "http://api.sunrise-sunset.org/json?lat=%f&lng=%f&formatted=0" % (lat, long)
f = requests.get(link)
data = f.text
sunrise = data[34:42]
sunset = data[71:79]
print("Sunrise = %s, Sunset = %s" % (sunrise, sunset))
s1 = sunrise
s2 = sunset
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
daylight = timedelta(days=0,seconds=tdelta.seconds, microseconds=tdelta.microseconds)
print('Total daylight = %s' % daylight)
t1 = datetime.strptime(str(daylight), '%H:%M:%S')
t2 = datetime(1900, 1, 1)
daylight_as_minutes = (t1 - t2).total_seconds() / 60.0
print('Daylight in minutes = %s' % daylight_as_minutes)
sr1 = datetime.strptime(str(sunrise), '%H:%M:%S')
sr2 = datetime(1900, 1, 1)
sunrise_as_minutes = (sr1 - sr2).total_seconds() / 60.0
print('Sunrise in minutes = %s' % sunrise_as_minutes)
ss1 = datetime.strptime(str(sunset), '%H:%M:%S')
ss2 = datetime(1900, 1, 1)
sunset_as_minutes = (ss1 - ss2).total_seconds() / 60.0
print('Sunset in minutes = %s' % sunset_as_minutes)
if __name__ == '__main__':
get_sunrise_sunset(42.9633599,-86.6680863)
I want to get start time and end time of yesterday linux timestamp
import time
startDay = time.strftime('%Y-%m-%d 00:00:00')
print startDay
endDay =time.strftime('%Y-%m-%d 23:59:59')
print endDay
Output is:
2016-11-18 00:00:00
2016-11-18 23:59:59
this showing in string today start-time and end-time
I want to get yesterday start-time and end-time in linux time-stamp
like:
4319395200
4319481599
import time
def datetime_timestamp(dt):
time.strptime(dt, '%Y-%m-%d %H:%M:%S')
s = time.mktime(time.strptime(dt, '%Y-%m-%d %H:%M:%S'))
return int(s)
import datetime
midnight2 = datetime.datetime.now().replace(hour=0,minute=0,second=0, microsecond=0)
midnight2 = midnight2 - datetime.timedelta(seconds= +1)
midnight1 = midnight2 - datetime.timedelta(days= +1, seconds= -1)
base = datetime.datetime.fromtimestamp(0)
yesterday = (midnight1 - base).total_seconds()
thismorning = (midnight2 - base).total_seconds()
print midnight1,"timestamp",int(yesterday)
print midnight2,"timestamp",int(thismorning)
print "Seconds elapsed",thismorning - yesterday
Result as of 18/11/2016 :
2016-11-17 00:00:00 timestamp 1479337200
2016-11-17 23:59:59 timestamp 1479423599
Seconds elapsed 86399.0
from datetime import datetime, date, time, timedelta
# get start of today
dt = datetime.combine(date.today(), time(0, 0, 0))
# start of yesterday = one day before start of today
sday_timestamp = int((dt - timedelta(days=1)).timestamp())
# end of yesterday = one second before start of today
eday_timestamp = int((dt - timedelta(seconds=1)).timestamp())
print(sday_timestamp)
print(eday_timestamp)
Or:
# get timestamp of start of today
dt_timestamp = int(datetime.combine(date.today(), time(0, 0, 0)).timestamp())
# start of yesterday = start of today - 86400 seconds
sday_timestamp = dt_timestamp - 86400
# end of yesterday = start of today - 1 second
eday_timestamp = dt_timestamp - 1
Use the power of perl command , no need to import time.
Startday=$(perl -e 'use POSIX;print strftime "%Y-%-m-%d 00:00:00",localtime time-86400;')
Endday=$(perl -e 'use POSIX;print strftime "%Y-%-m-%d 23:59:59",localtime time-86400;')
echo $Startday
echo $Endday
or
startday=date --date='1 day ago' +%Y%m%d\t00:00:00
startday=date --date='1 day ago' +%Y%m%d\t23:59:59
echo $Startday
echo $Endday