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'
Related
For the node 'TransactionDate' i have a logic before updating it for policy"POL000002NGJ".
The logic i am trying to implement is If existing 'TransactionDate' < than today, then add 5 days with current value and parse it to xml.
Transaction Date Format in XML : 2020-03-23T10:56:15.00
Please Note that, If i parsing the DateTime value like below, It works good But i dont want to hardcode the value... I want to Parse it as a string object to handle for any datetime in format ""%Y-%m-%dT%H:%M:%S.%f""...
# <TransactionDate>
today = datetime.now()
TransactionDate = doc.find('TransactionDate')
Date = '2020-03-24T10:56:15.00'
previous_update = datetime.strptime(Date, "%Y-%m-%dT%H:%M:%S.%f")
if previous_update < today:
today = previous_update - timedelta(days=-5)
TransactionDate = today.strftime("%Y-%m-%dT%H:%M:%S.%f")
Below code while parsing it as a DateTime Object, I have an issue.. I got struck here and referenced other answers in stackoverflow and python forums, But still i got struct up here and unable to resolve the issue...
if any help to fix will be a great helpful. Thanks. Below code using lxml and getting help to support below code will helpful. Because i already completed for other nodes. My understanding is Date variable is calling as None.. But struck here to fix.. Please help..
# <TransactionDate>
today = datetime.now()
TransactionDate = doc.find('TransactionDate')
Date = str(TransactionDate)
previous_update = datetime.strptime(Date, "%Y-%m-%dT%H:%M:%S.%f")
if previous_update < today:
today = previous_update - timedelta(days=-5)
TransactionDate = today.strftime("%Y-%m-%dT%H:%M:%S.%f")
Full Code is Below
from lxml import etree
from datetime import datetime, timedelta
import random, string
doc = etree.parse(r'C:\Users\python.xml')
# <PolicyId> - Random generated policy number
Policy_Random_Choice = 'POL' + ''.join(random.choices(string.digits, k=6)) + 'NGJ'
# <TransactionDate>
today = datetime.now()
TransactionDate = doc.find('TransactionDate')
Date = str(TransactionDate)
previous_update = datetime.strptime(Date, "%Y-%m-%dT%H:%M:%S.%f")
if previous_update < today:
today = previous_update - timedelta(days=-5)
TransactionDate = today.strftime("%Y-%m-%dT%H:%M:%S.%f")
#Parsing the Variables
replacements = [Policy_Random_Choice , TransactionDate ]
targets = doc.xpath('//ROW[PolicyId="POL000002NGJ"]')
for target in targets:
target.xpath('./PolicyId')[0].text = replacements[0]
target.xpath('.//TransactionDate')[0].text = replacements[1]
print(etree.tostring(doc).decode())
Sample XML
<TABLE>
<ROW>
<PolicyId>POL000002NGJ</PolicyId>
<BusinessCoverageCode>COV00002D3X1</BusinessCoverageCode>
<TransactionDate>2020-03-23T10:56:15.00</TransactionDate>
</ROW>
<ROW>
<PolicyId>POL111111NGJ</PolicyId>
<BusinessCoverageCode>COV00002D3X4</BusinessCoverageCode>
<TransactionDate>2020-03-23T10:56:15.00</TransactionDate>
</ROW>
</TABLE>
Maybe the find method is wrong. Try this one
# <TransactionDate>
today = datetime.now()
TransactionDate = doc.xpath('//ROW/TransactionDate') # Change find to xpath
Date = str(TransactionDate[0].text) # Use the first one
previous_update = datetime.strptime(Date, "%Y-%m-%dT%H:%M:%S.%f")
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')
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())
what i wanted to do with this code is get all the datas thats dated older than yesterday. It throws an error "an integer is required" at the line:
date = datetime.date(year, month, yesterday)
So far to my knowledge, its taking year as an integer but not month field. It takes the month field as the default datetime field.
Heres my view:
current = datetime.datetime.now()
yesterday = datetime.datetime.today() + datetime.timedelta(days = -1)
year = datetime.date.today().year
month = datetime.date.today() + relativedelta(months = -1)
date = datetime.date(year, month, yesterday)
hist_obj = Events.objects.filter(uploader = request.user,
start_date__lte = date)
return render_to_response('history.html', {'history_obj':hist_obj})
This code is confusing. yesterday and month are both datetimes, because that's how you defined them in lines 2 and 4. So what are you trying to achieve in the code that throws the error? As the message says, you can't pass a datetime as the day or month parameter to construct another datetime. Especially as, surely, yesterday is already the date that you want? Why can't you simply pass that to the query?
Try this,
day_ago = datetime.date.today() - datetime.timedelta(days=1)
yesterday = datetime.datetime(day_ago.year, day_ago.month, day_ago.day)
hist_obj = Events.objects.filter(uploader = request.user,
start_date__lt = yesterday)
return render_to_response('history.html', {'history_obj':hist_obj})
I'm attempting to craft a function that takes a time object and converts it to UTC time. The code below appears to be off by one hour. When i run noon through the converter, i get back 18:00:00. But when i run the same data through online converters, i get 17:00:00.
What am i doing wrong here? Any help would be greatly appreciated.
import pytz, datetime
def convert_to_utc(time, tz):
now_dt = datetime.datetime.utcnow()
#get a date object
date_dt = now_dt.date()
#combine the current date object with our given time object
dt = datetime.datetime.combine(date_dt, time)
#get an timezone object for the source timezone
src_tz = pytz.timezone(str(tz))
#stamp the source datetime object with the src timezone
src_dt = dt.replace(tzinfo=src_tz)
#get the offset from utc to given timezone
offset = str(int(src_dt.strftime("%z"))).rstrip('0')
#convert the source datetime object to
utc_dt = src_dt.astimezone(pytz.utc)
#return the converted time and the offset in integer format
return (utc_dt.time(), int(offset))
time = datetime.datetime.strptime('12:00:00', "%H:%M:%S").time()
(TIME, offset) = convert_to_utc(time, 'America/Chicago')
print TIME.strftime("%H:%M:%S")
**EDIT**
Here's the updated(and functional) code in case anyone else needs help converting to/from UTC.
Thanks everyone for your help!
import pytz, datetime
def convert_to_utc(time, tz): #this returns the offset in int form as well
now_dt = datetime.datetime.utcnow()
#get a date object
date_dt = now_dt.date()
#combine the current date object with our given time object
dt = datetime.datetime.combine(date_dt, time)
#get an timezone object for the source timezone
src_tz = pytz.timezone(str(tz))
#stamp the source datetime object with the src timezone
src_dt = src_tz.localize(dt)
#get the offset from utc to given timezone
offset = str(int(src_dt.strftime("%z"))).rstrip('0')
#convert the source datetime object to
utc_dt = src_dt.astimezone(pytz.utc)
#return the converted time and the offset in integer format
return (utc_dt.time(), int(offset))
def convert_from_utc(time, tz):
now_dt = datetime.datetime.now()
date = now_dt.date()
dt = datetime.datetime.combine(date, time)
dest = pytz.timezone(str(tz))
dt = dt.replace(tzinfo=pytz.utc)
dest_dt = dt.astimezone(dest)
return dest_dt.time()
time = datetime.datetime.strptime('12:00:00', "%H:%M:%S").time()
(TIME, offset) = convert_to_utc(time, 'America/Chicago')
print TIME.strftime("%H:%M:%S")
utc_time = datetime.datetime.strptime('17:00:00', "%H:%M:%S").time()
TIME = convert_from_utc(utc_time, 'America/Chicago')
print TIME.strftime("%H:%M:%S")
Change
src_dt = dt.replace(tzinfo=src_tz)
to
src_dt = src_tz.localize(dt)
Using localize adjusts for Daylight Savings Time, while replace does not.
See the section entitled "Localized times and date arithmetic" in the docs.
To convert time in given timezone to UTC time:
from datetime import datetime
import pytz
def convert_to_utc(time, tzname, date=None, is_dst=None):
tz = pytz.timezone(tzname)
if date is None: # use date from current local time in tz
date = datetime.now(tz).date()
dt = tz.localize(datetime.combine(date, time), is_dst=is_dst)
return dt.astimezone(pytz.utc).time(), dt.utcoffset().total_seconds()
if is_dst is None it raises an exception for ambiguous local times.
To convert UTC time to local time in given timezone:
def convert_from_utc(time, tzname, date=None):
tz = pytz.timezone(tzname)
if date is None: # use date from current time in utc
date = datetime.utcnow().date()
dt = datetime.combine(date, time).replace(tzinfo=pytz.utc)
return tz.normalize(dt.astimezone(tz)).time()
Example:
time = datetime.strptime('12:00:00', "%H:%M:%S").time()
utc_time, offset = convert_to_utc(time, 'America/Chicago')
print utc_time.strftime("%H:%M:%S"), offset # -> 17:00:00 -18000.0
utc_time = datetime.strptime('17:00:00', "%H:%M:%S").time()
time = convert_from_utc(utc_time, 'America/Chicago')
print time.strftime("%H:%M:%S") # -> 12:00:00
In general it is preferable to work with full datetime objects to avoid ambiguity with what is the correct date i.e., pass and return datetime objects.
By using the replace method on the datetime, you're not allowing the time zone to be adjusted for daylight savings time. Try using one of the documented methods from the pytz documentation:
src_dt = src_tz.localize(dt)