I'd like to make my code a little more user-friendly such that when users post something, i'd like it to say "x seconds/hour/day ago"
so far my code is
{{ post.date_posted.strftime('%Y-%m-%d %H:%M:%S') }}
You want datetime.timedelta()
import datetime
import time
old_time = datetime.datetime.now()
time.sleep(20)
new_time = datetime.datetime.now()
# The below line returns a 'timedelta' object.
delta = new_time - old_time
print('{} seconds have passed.'.format(delta.total_seconds()))
# or
print(
'{} days, {} hours, {} minutes, {} seconds passed.'.format(
delta.days,
delta.seconds//3600,
(delta.seconds//60)%60,
int(delta.total_seconds()%60)))
I believe it also exists for just date and time modules as well.
Related
I am new to Python and am having a hard time filtering an api request by datetime: tomorrow basically from hours 0100-2400, only. Time zone is local time. The request prints out as a nested dictionary and I have been able to filter it down to 'validTime' but can't get it filtered anymore from there. My start_time and end_time may be wrong, or my if statement may be wrong, or it's something else. I feel that there is an easy fix for this, I just can't figure it out. Please help. My code is below:
import constants
import requests
import datetime
import json
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
tomorrow = today + datetime.timedelta(days=1)
day_after_tomorrow = today + datetime.timedelta(days=2)
hour1 = datetime.time(1, 0, 0)
hour0 = datetime.time(0, 0, 0)
start_time = ['{}T{}+00:00/PT1H'.format(tomorrow, hour1)]
end_time = ['{}T{}+00:00/PT1H'.format(day_after_tomorrow, hour0)]
response = requests.get(constants.austinfgd, headers=headers)
data = json.loads(response.text)
temperature_data = data['properties']['temperature']['values']
print(temperature_data)
This is what is printed out to this point:
Printed response to temperature_data from website
[{'validTime': '2020-12-11T10:00:00+00:00/PT2H', 'value': 17.77777777777778},
{'validTime': '2020-12-11T12:00:00+00:00/PT1H', 'value': 16.666666666666668},
{'validTime': '2020-12-11T13:00:00+00:00/PT2H', 'value': 17.22222222222222},
...
and so on for a number of days
So, now I need to filter by validTime and I specifically want the hours = to and in between start_time and end_time. So, here is my code for that:
for v in temperature_data:
if ['validTime'] >= start_time and ['validTime'] <= end_time:
At this point, pycharm is telling me to simplifiy the chained comparison and it automatically gives me this:
for v in temperature_data:
if start_time <= ['validTime'] <= end_time:
print(v)
At this point, the only thing that prints out is:
Printed response to v
Process finished with exit code 0
I need to print these values by these times only, so I can dump into a table in postgresql, to be used elsewhere.
What am I doing wrong? I have been googling this for over a week, and I give up. Time to ask for help, please help. Thank you in advance for your help.
So, I changed things up and this seems to have worked. Not sure if there is a better way to code this. And I don't understand why I need to have v['validTime'] in the if statement. Is there a cleaner way to do this?
tomorrow = datetime.datetime.combine(
datetime.date.today() + datetime.timedelta(days=1),
datetime.time(1, 0, 0),
tzinfo=pytz.UTC
)
day_after_tomorrow = datetime.datetime.combine(
datetime.date.today() + datetime.timedelta(days=2),
datetime.time(1, 0, 0),
tzinfo=pytz.UTC
)
start_time = tomorrow.isoformat()
end_time = day_after_tomorrow.isoformat()
response = requests.get(constants.austinfgd, headers=headers)
data = json.loads(response.text)
temperature_data = data['properties']['temperature']['values']
for v in temperature_data:
if start_time <= v['validTime'] <= end_time:
print(v)
Good evening, could you help me in how I can put a condition so that a message comes out saying that you can not take an hour because it is already busy ?, I currently have this:
class reserva (models.Model):
_name='gimnasio.reserva'
tipo_reserva=fields.Selection([('clase','Clase'),('evaluacion','Evaluacion')])
fecha_reserva=fields.Date()
start_time=fields.Float()
end_time=fields.Float()
def fecha(self):
if self.star_time==self.star_time:
raise validationError('the hour is busy')
I have another question for you. you know how to configure Datetime only for hour and minutes because I only need hour and minutes but not the date.
To configure Datetime only for hour and minutes.
time = fields.Datetime("time")
custom_time = fields.Char('my_custome_time')
#api.onchange('time')
def _get_time(self):
if self.time:
for rec in self:
# datetime value is a string like 'YYYY-mm-dd HH:MM:SS'
# so just extract string from position 11 to 16
_time = self.time[11:16]
self.custom_time = _time
rec.custom_time = self.custom_time
I think you can use strptime method from datetime module.
from datetime import datetime as dt
start_time = fields.Float()
end_time = fields.Float()
#api.onchange('start_time','end_time')
def _check(self):
records = self.env["gimnasio.reserva"].search([("day", '=', the day you want to check eg. "2019-06-13")])
for rec in records:
ref_start = dt.strptime(str(rec.start_time), "%H:%M")
curr_start = dt.strptime(str(self.start_time), "%H:%M")
if ref_start == curr_start:
raise validationError('the hour is busy')
I didn't debug yet, you can try it.
how to eliminate the default date that you added ("2019-06-13") and that any date should not have the same busy schedule?
In this case you don't need datetime module just
#api.constrains("start_time")
def _check(self):
# search db for any record have same start time.
records = self.env["gimnasio.reserva"].search([('start_time ','=', self.start_time)])
if len(records) > 0:
raise validationError('the hour is busy')
Hi I am having trouble getting the time two hours ago in a similar function to my get_timestamp =>
def get_timestamp():
"""Return correctly formatted timestamp"""
return strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
def two_hours_ago():
"""Return correctly formatted timestamp"""
last = (date.today() - timedelta(hours=1))
return strftime("%Y-%m-%dT%H:%M:%SZ", gmtime()-'2HOURS')
I tried this:
def two_hours_ago():
"""Return correctly formatted timestamp"""
today = date.today()
yesterday = (today - timedelta(hours=2))
print(yesterday.timetuple())
return strftime("%Y-%m-%dT%H:%M:%SZ", yesterday.timetuple())
UPDATE
thank you
Huang Yen Hao
I was looking for a 2 hour interval returned in ISO format for Amazon MWS, I used the following functions to return the correctly formatted time.
def two_hours_ago():
"""Return correctly formatted timestamp"""
now = datetime.now()
two_hours_ago = (now - timedelta(hours=2))
return two_hours_ago.strftime("%Y-%m-%dT%H:%M:%SZ")
def now():
"""Return correctly formatted timestamp"""
now = datetime.now()
two_hours_ago = (now - timedelta(hours=0))
return two_hours_ago.strftime("%Y-%m-%dT%H:%M:%SZ")
I don't really understand the code that is today = date.today().
Is it means, for example, 2017/10/18 00:00:00?
The following code can get time two hours ago. I am not sure what you what is it or not..
from datetime import datetime, timedelta
def two_hours_ago():
"""Return correctly formatted timestamp"""
now = datetime.now()
two_hours_ago = (now - timedelta(hours=2))
return two_hours_ago.strftime("%Y-%m-%dT%H:%M:%SZ")
For this code, it will perform like following
>>> two_hours_ago()
'2017-10-19T11:28:40Z'
I'm currently learning Python and taken it upon myself to learn some data validation. One part I've gotten stuck on is date and time validation. This program takes a number of parameters including date_start, time_start, date_end, and time_end. The catch is I need them in ISO format. Once in that format I need to make sure they are valid. That's where I'm stuck.
from datetime import datetime
def validate_date(date_start, time_start, date_end, time_end):
full_date_start = date_start + time_start
full_date_end = date_end + time_end
try:
formatted_time_start = datetime.strptime(full_date_start, "%Y-%m-%d%H:%M:%S").isoformat(sep="T", timespec="seconds")
formatted_time_end = datetime.strptime(full_date_end, "%Y-%m-%d%H:%M:%S").isoformat(sep="T", timespec="seconds")
return True
except ValueError:
return False
date_start = "2017-06-29"
time_start = "16:24:00"
date_end = "2017-06-"
time_end = "16:50:30"
print(validate_date(date_start, time_start, date_end, time_end))
print("Date Start: " + date_start + "\nTime Start: " + time_start + "\nDate End: " + date_end + "\nTime End: " + time_end)
I was testing some of the code by removing the day for date_end and the output I got back was
2017-06-01T06:50:30
This check should have failed, or I believe it should have since a day was not supplied. Any help would be appreciated and if there is an easier way to do this, I'd take it. Thank you!
If you check the value of full_date_end before the line that should fail is executed, you get this: "2017-06-16:50:30" and since the format you are looking for looks like this "%Y-%m-%d%H:%M:%S" it picks up the first digit of 16 as the day value and the second digit as the hour value.
To avoid this I would suggest using this format: "%Y-%m-%d %H:%M:%S" as the second parameter of the strptime call. But this also requires for you to change the lines where you define full_date_start and full_date_end as:
full_date_start = date_start + ' ' + time_start
full_date_end = date_end + ' ' + time_end
try:
formatted_time_start = datetime.strptime(full_date_start, "%Y-%m-%d %H:%M:%S").isoformat(sep="T", timespec="seconds")
formatted_time_end = datetime.strptime(full_date_end, "%Y-%m-%d %H:%M:%S").isoformat(sep="T", timespec="seconds")
...
I hope that solves your problem.
I currently have:
#classmethod
def get_past_week(self):
start_date = datetime.now().date()
end_date = datetime.now().date() - timedelta(weeks=1)
return MyModel.objects.filter(pub_date__range=(end_date, start_date)).aggregate(Sum('off_hours'))
which simply pulls all posts from the current date minus 7 days
I want to pull posts from within the same day factoring in the time at the moment. Thus if the time is 15:00 GMT now, I want all posts from 14:59:49 GMT back to 00:00:01 GMT of the same day. How can I do something like that?
I've tried something like (not work
def get_today_hours(self):
start_time = datetime.now().time()
end_time = datetime.now().time() - timedelta(hours=datetime.today().hour, minutes=0, seconds=0)
return MyModel.objects.filter(pub_date__range=(end_time, start_time))
According to this post on SO, there's a way to get items from same day by using CURDATE()
You can do the following
end_time = datetime.now()
start_time = datetime(end_time.year,end_time.month,end_time.day)
That will set end_time to actual time, and start_time to the same day as end_time, but with the time at 0 hours and 0 seconds.
How about this:
from datetime import datetime, timedelta
end_time = datetime.now()
start_time = datetime.combine(end_time, datetime.min.time()) #Reset the hours/time offset
qs = MyModel.objects.filter(pub_date__range=(start_time, end_time))
Or something even simpler:
qs = MyModel.objects.filter(pub_date__startswith=end_time.date())