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
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/
im currently getting this error
Traceback (most recent call last):
File "/Users/user/Documents/test.py", line 44, in <module>
get_slots(hours, appointments)
File "/Users/user/Documents/test.py", line 36, in get_slots
while start + duration <= end:
TypeError: coercing to Unicode: need string or buffer, datetime.timedelta found
My code:
from datetime import timedelta
import datetime
#notice the additional brackets to keep the 2 slots as two separate lists. So, 930-1230 is one slot, 1330-1400 is an another.
# HOURS AND APPOINTMENTS ARE GENERATED BY GATHERING DATA FROM DATABASE
hours = [[u'08:00', u'17:00']]
appointments = [(u'12:00', u'12:30'), (u'10:30', u'11:00')]
def get_slots(hours, appointments, duration=timedelta(hours=1)):
slots = sorted([(hours[0][0], hours[0][0])] + appointments + [(hours[0][1], hours[0][1])])
for start, end in ((slots[i][1], slots[i+1][0]) for i in range(len(slots)-1)):
assert start <= end, "Cannot attend all appointments"
while start + duration <= end:
json = []
json.append("{:%H:%M} - {:%H:%M}".format(start, start + duration))
start += duration
return json
if __name__ == "__main__":
get_slots(hours, appointments)
The code should output something like:
09:00 - 10:00
10:30 - 11:30
13:00 - 14:00
14:00 - 15:00
I found this code from Python - finding time slots
You have to convert both start and end string to datetime objects. See below example:
from datetime import timedelta
import datetime
#notice the additional brackets to keep the 2 slots as two separate lists. So, 930-1230 is one slot, 1330-1400 is an another.
# HOURS AND APPOINTMENTS ARE GENERATED BY GATHERING DATA FROM DATABASE
hours = [[u'08:00', u'17:00']]
appointments = [(u'12:00', u'12:30'), (u'10:30', u'11:00')]
def get_slots(hours, appointments, duration=timedelta(hours=1)):
slots = sorted([(hours[0][0], hours[0][0])] + appointments + [(hours[0][1], hours[0][1])])
for start, end in ((slots[i][1], slots[i+1][0]) for i in range(len(slots)-1)):
start = datetime.datetime.strptime(start, "%H:%M")
end = datetime.datetime.strptime(end, "%H:%M")
print(start+duration)
assert start <= end, "Cannot attend all appointments"
while start + duration <= end:
json = []
json.append("{:%H:%M} - {:%H:%M}".format(start, start + duration))
start += duration
return json
if __name__ == "__main__":
x = get_slots(hours, appointments)
I have an API to which I have to send a epoch time start and end date. The only issue is that it will not accept microseconds.
I built a time function using datatime, however it calculates the microseconds. I tried the .replace(microsecond=0), but that just leaves the .0 on the Epoch, which my API complains about. I also tried exporting to strptime, but then my .timestamp function fails to parse it as a string.
timestart = datetime.now() - timedelta(hours = 24)
timeend = datetime.now()
params = {'start_date':timestart.timestamp(), 'end_date':timeend.timestamp()}
i would like to basically calculate current time in Epoch and time 24 hours ago (this does not have to be super precise) that I can pass to my API.
You can simply cast (Type Conversion) the values of timestart.timestamp() and timeend.timestamp(), which are floats, to ints, i.e.:
from datetime import datetime, timedelta
timestart = datetime.now() - timedelta(hours = 24)
timeend = datetime.now()
s = int(timestart.timestamp())
e = int(timeend.timestamp())
params = {'start_date':s, 'end_date':e}
print(params)
Output:
{'start_date': 1554121647, 'end_date': 1554208047}
Demo
I usually use time.mktime() for converting datetimes to epoch time:
from datetime import datetime, timedelta
import time
timestart = datetime.now() - timedelta(hours = 24)
timeend = datetime.now()
params = {
'start_date': int(time.mktime(timestart.timetuple())),
'end_date': int(time.mktime(timeend.timetuple()))
}
# Output
{'start_date': 1554123099, 'end_date': 1554209499}
An alternative solution to Pedro's one:
from datetime import datetime
from datetime import timedelta
timestart = (datetime.now() - timedelta(hours = 24)).strftime("%s")
timeend = datetime.now().strftime("%s")
params = {'start_date':timestart,
'end_date':timeend}
Output:
{'start_date': '1554124346', 'end_date': '1554210746'}
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