Setting datetime inside QDateTimeEdit widget - python

I have to set the date and time available as a string in the following format.
"%Y/%m/%d %H:%M:%S"
cur_time = strftime("%H:%M:%S", gmtime())
cur_date = DATA[1]
date_time = cur_date+" "+cur_time
now = QtCore.QDate.fromString(date_time, '%Y/%m/%d %H:%M:%S')
self.dateTimeEdit.setDate(now)
But this is not working.

The format of date and datetime is different from the format of QDate and QDateTime, you should not use% in the Qt format, check the docs for more detail:
Assuming DATA[1] has a format %Y/%m/%d as you try to use, you can use the following code:
cur_time = strftime("%H:%M:%S", gmtime())
cur_date = "2018/11/10"
date_time = cur_date+" "+cur_time
now = QtCore.QDateTime.fromString(date_time, 'yyyy/M/d hh:mm:ss')
self.dateTimeEdit.setDateTime(now)

Related

ValueError: time data 'None' does not match format '%Y-%m-%dT%H:%M:%S.%f'

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")

Python & Tweepy - How to compare and change times.

I am trying to create a number of constraints for some other code based on twitter handle sets.
I am having issues with the following code because:
TypeError: can't compare datetime.datetime to str
It seems that even though I have changed Last_Post to a datetime object initially, when i compare it to datetime.datetime.today() it is converting to string. Yes, I have checked the to ensure that Last_post is converting properly. Im not really sure what is going on. Help?
for handle in handles:
try:
user = api.get_user(handle)
#print json.dumps(user, indent = 4)
verified = user["verified"]
name = user['name']
language = user['lang']
follower_count = user['followers_count']
try:
last_post = user['status']['created_at']
last_post = datetime.strptime(last_post, '%a %b %d %H:%M:%S +0000 %Y')
except:
last_post = "User has not posted ever"
location = user['location']
location_ch = location_check(location)
if location_ch is not "United States":
location_output.append(False)
else:
location_output.append(True)
new_sum.append(follower_count)
if language is not "en":
lang_output.append(False)
else:
lang_output.append(True)
if datetime.datetime.today() - datetime.timedelta(days=30) > last_post:
recency.append(False)
else:
recency.append(True)
I think you need to convert the twitter date to a timestamp:
import time
ts = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tweet['created_at'],'%a %b %d %H:%M:%S +0000 %Y'))

How can i extract time from datetime.datetime object in odoo

This is my code:
shift_from = datetime.strptime(shift_change_ob.shift_date, '%Y-%m-%d %H:%M:%S')
shift_to = datetime.strptime(shift_change_ob.shift_date_to, '%Y-%m-%d %H:%M:%S')
shift_time_from = self.get_zone_time(shift_from)
shift_time_to= self.get_zone_time(shift_to)
time_from = datetime.strptime(str(shift_time_from),"%Y-%m-%d %H:%M:%S").strftime("%H.%M")
time_to = datetime.strptime(str(shift_time_to),"%Y-%m-%d %H:%M:%S").strftime("%H.%M")
I want to get only time from shift_time_from and shift_time_to. When I do this I get:
ValueError: unconverted data remains: +00:00
How can I solve this?
If shift_from and shift_to are correct, then use the method time for getting only time part:
shift_time_from = shift_from.time()
shift_time_to = shift_to.time()

converting from local to utc timezone

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)

ToscaWidgets CalendarDatePicker pylons

How does one set the date on the CalendarDatePicker. i.e. it defaults to current date and I want to display it with another date which I will set from my controller.
I am displaying the CalendarDatePicker widget in a TableForm from tw.form. I have looked at this for a few hours and can't work out how to do this so any pointers greatly appreciated.
import tw.forms as twf
form = twf.TableForm('dateSel', action='changeDate', children=[
twf.CalendarDatePicker('StartDate', date_format = "%d/%m/%Y"),
twf.CalendarDatePicker('EndDate', date_format = "%d/%m/%Y" )
])
I don't have a copy of twforms laying around, but based on their sample code, it looks like you might want to do something like:
from datetime import datetime
start = twf.CalendarDatePicker('StartDate', date_format = "%d/%m/%Y")
start.default = datetime.now() # or any valid datetime object
end = twf.CalendarDatePicker('EndDate', date_format = "%d/%m/%Y" )
start.default = datetime.now() # or any valid datetime object
form = twf.TableForm('dateSel', action='changeDate', children=[start, end])

Categories