Retrieving free/busy status from microsoft outlook using python - python

I'm trying to retrieving free/busy status from outlook calender for particular person using python language.
here is my code for it.
import win32com.client
obj_outlook = win32com.client.Dispatch('Outlook.Application')
obj_Namespace = obj_outlook.GetNamespace("MAPI")
obj_Recipient = obj_Namespace.CreateRecipient("someone#domain.com")
str_Free_Busy_Data = obj_Recipient.FreeBusy("11-11-2013", 11)
print str_Free_Busy_Data
but I'm getting an error:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
str_Free_Busy_Data = obj_Recipient.FreeBusy("11-11-2013", 11)
File "<COMObject CreateRecipient>", line 4, in FreeBusy
TypeError: an integer is required
So my question is Recipient.FreeBusy() method takes two mandatory arguments, Start Date and duration. Here 11 is the duration, which is an Integer. So why python is not able to identify the integer argument here and returning an TypeError.
Please help me in case I have done anything wrong (I'm still a newbie in python world).
Thanks in advance.

I looked up the method in MSDN.
http://msdn.microsoft.com/en-us/library/office/microsoft.office.interop.outlook.recipient.freebusy(v=office.12).aspx
The syntax for the method takes 3 arguments.
string FreeBusy(
DateTime Start,
int MinPerChar,
Object CompleteFormat
)
The issue is that you're passing a string to the DateTime parameter. Instead you need to import the datetime library in your code and use a date parameter.
So, at the start of your code, try this.
import datetime
#Then declare the my_date variable as datetime.date.
my_date = datetime.date(2013,11,23)
str_Free_Busy_Data = obj_Recipient.FreeBusy(my_date, 11)

The first parameter to FreeBusy is a Date object. Pywin won't convert a string into a Date , but it can convert a pywintypes.Time object, or an integer representing the number of seconds since the Unix epoch. Hence the error: When the first argument is implicitly converted to a Time, the constructor complains that it needs an integer.
#start date: 12/31/1969 7:00:00 PM
str_Free_Busy_Data = obj_Recipient.FreeBusy(0, 11)
There are a number of ways to get the Unix timestamp from a date. See Convert python datetime to epoch with strftime.

Related

Python Faker Datetime Generation returns tuple with datetime in it - instead just datetime

for testing purposes i want to compare two datetime objects.
dt1 = fake.date_time() # assumming 2021-03-25 08:56:12
dt1 structure
dt2 = datetime.datetime.strptime('2021-03-25 08:56:12', "%Y-%m-%d %H:%M:%S")
dt2 structure
The comparision fails as i try to compare a datetime object with a tuple which has a datetime object in it.
If I try to just assign the first element of the tuple (dt1) like so:
dt1 = fake.date_time()[0]
I get the follow error:
Error directly assign tuple element
But if i do the following, it works:
dt1 = fake.date_time()
dt1 = dt1[0]
What do I not understand here? :( And why isn't faker directly returning a datetime?
Thank you for any help.
I use python 3.7 and faker 6.6.2.
As I was preparing the whole code to be passed here, I discovered the issue.
I copied this line from a dict definition, and it had the comma at the end...
dt = fake.date_time(),
Obviously then python creates a tuple, I just didn't see this.
If you check the Faker date_time function source code you'll see only a single datetime.datetime object retuns:
def date_time(self, tzinfo=None, end_datetime=None):
"""
Get a datetime object for a date between January 1, 1970 and now
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('2005-08-16 20:39:21')
:return datetime
"""
# NOTE: On windows, the lowest value you can get from windows is 86400
# on the first day. Known python issue:
# https://bugs.python.org/issue30684
return datetime(1970, 1, 1, tzinfo=tzinfo) + \
timedelta(seconds=self.unix_time(end_datetime=end_datetime))
I suspect an unwanted change has been applied to the dt1 object (or it can be a debugger bug also), as I can see in the error clearly stated that the datetime.datetime object is not subscriptable . Would you add the complete code for further checking?

Python 3.6 - getting error 'an integer is required (got type str)' while converting some strings to time

I wrote a function that takes in a row that has some raw numeric data in one of the columns and converts it to appropriate minutes (its a csv file). All the columns have been kept as strings if at all I need to wrangle with them since strings makes it easier. However, when converting some data into time format (again in strings), I get the error described in the title. My functions looks like the following:
def duration_in_mins(row, city):
duration = [] # Make an empty list
form = '%M.%S'
if city == 'X':
city_file = open('X.csv')
city_csv = csv.reader(city_file)
for row in city_csv:
duration.append(row[1]) # The column that contains the strings
for i in duration:
datetime.datetime.fromtimestamp(i).strftime(form, 'minutes') # Conversion
else:
return 'Error'
return duration
The line datetime.datetime.fromtimestamp(i).strftime(form, 'minutes') is where I'm getting the error according to traceback when I run duration_in_mins(). Is the traceback telling me to convert the string into numeric first and then to time? Can datetime not convert strings directly into time?
duration_in_mins(5, 'X)
line 39, in duration_in_mins
datetime.datetime.fromtimestamp(i).strptime(form, 'minutes')
TypeError: an integer is required (got type str)
As you say, datetime.fromtimestamp() requires a number but you are giving it a string. Python has a philosophy "In the face of ambiguity, refuse the temptation to guess" so it will throw an exception if you give a function an object of the wrong type.
Other problems with the code:
The strftime() method will only take one argument but you're
passing it a second one.
Also, did you mean to nest those loops? Every time you append another
value to duration you convert all of the values in the list to times, and
then if the conversion did work you are just throwing away the result
of the conversion and not saving it anywhere.
First, there is an incoherence between your code and the reported error:
datetime.datetime.fromtimestamp(i).strftime(form, 'minutes') # Conversion
and
line 39, in duration_in_mins
datetime.datetime.fromtimestamp(i).strptime(form, 'minutes')
TypeError: an integer is required (got type str)
Please note strptime is different than strftime
Then, you should split the line with error to understand what function exactly caused the exception:
x = datetime.datetime.fromtimestamp(i)
x.strftime(form, 'minutes') # Conversion
And you will probably see that the error comes from fromtimestamp(ts) which needs an integer timestamp argument instead of a str.
Convert this argument as int at some point and everything should be ok.

django convert to date type (TypeError)

I'm trying to get data from excel cells (number format) and convert them to date type in Django 1.7.7:
import datetime as dt
birthdate =dt.date.fromtimestamp(sheet.row_values(idx)[63]).strftime('%Y-%m-%d')
but got this error:
File "t3_import2.py", line 46, in <module>
birthdate =dt.date.fromtimestamp(sheet.row_values(idx)[63]).strftime('%Y-%m-%d')
TypeError: a float is required
Why is it complaining when I explicitly cast it to float?
sheet.row_values(idx)[63] is not a float.
If I understand right, fromtimestamp expects a POSIX timestamp, which is a vector representing the number of seconds elapsed from a given time to the time/date it represents. I can't see what sheet.row_values(idx)[63] is from your post, but I'd bet Python it taking it as an int.
classmethod date.fromtimestamp(timestamp)¶
Return the local date
corresponding to the POSIX timestamp, such as is returned by
time.time(). This may raise ValueError, if the timestamp is out of the
range of values supported by the platform C localtime() function. It’s
common for this to be restricted to years from 1970 through 2038. Note
that on non-POSIX systems that include leap seconds in their notion of
a timestamp, leap seconds are ignored by fromtimestamp().
try this:
x = float(sheet.row_values(idx)[63])
birthdate = dt.date.fromtimestamp(x).strftime('%Y-%m-%d')

Python 2.7 Converting standard unix timestamps to epoch time

I am trying to convert a time stamp of the format 20151021|133102[-0400/1] into an epoch time.
I want the code to run regardless of the native timezone of the machine it is running on, and be DST aware so the code will run over the switch to/from DST. I need the code to run under Python 2.7.x (ideally using only standard library modules so the code is portable.)
After wasting the afternoon googling, the best I have been able to do is:
time.mktime(time.strptime('20151021|133102','%Y%m%d|%H%M%S'))`
which does not allow me to incorporate either the offset, or the daylight savings flag.
I also tried the following:
time.mktime(time.strptime('20151021|133102-4000','%Y%m%d|%H%M%S%z'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_strptime.py", line 467, in _strptime_time
return _strptime(data_string, format)[0]
File "/usr/lib/python2.7/_strptime.py", line 317, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y%m%d|%H%M%S%z'
but it seems that strptime does not allow the offset.
strptime does support:
time.mktime(time.strptime('20151021|133102EDT','%Y%m%d|%H%M%S%Z'))
but this means that I need to somehow convert the offset into a timezone abbreviation which seems sort of stupid--and might create an error depending on where the code is run.
I can't believe this isn't more straight forward given routine this problem should be. Any assistance would be much appreciated.
There are two steps:
parse the time string into a date/time object e.g., How to parse dates with -0400 timezone string in python? and
Parsing date with timezone from an email?
import time
time_string = "20151021|133102-0400"
tt = time.strptime(time_string[:15], "%Y%m%d|%H%M%S")
hours, minutes = divmod(int(time_string[16:]), 100)
utc_offset = (hours * 60 + minutes) * 60
if time_string[15] == '-':
utc_offset = -utc_offset
get "seconds since the Epoch" that corresponds to the date/time object: Converting datetime.date to UTC timestamp in Python
from calendar import timegm
posix_timestamp = timegm(tt) - utc_offset
I want the code to run regardless of the native timezone of the machine it is running on
time.mktime() expects local time as an input. Don't use it if the input time string does not represent local time. You also shouldn't use it if the time string has the utc offset (mktime() may produce a wrong result for ambiguous times or past/future dates).
First off you are identifying the numbers as a string. What I did was identify the string as an integer and then use datatime to convert into epoche time.
You'll need to remove the symbols not identified as an integer to have the following number listed above but the code below works for me on python 2.7
import datetime
conversion = datetime.datetime.fromtimestamp(int("20151021")).strftime('%Y-%m-%d %H:%M:%S')
print (conversion)
Weird. Works in Python3, but not Python2
>>> time.mktime(time.strptime('20151021|133102-0400', '%Y%m%d|%H%M%S%z'))
1445452262.0

How to use python date time function/ increment?

I read many of the similar questions, the function is simple nested for loops used for the API, each minute I can call 5 times. So I set the range of 75 for one year data. Can you guys help me solve the problem? Thanks in advance!
The first part is working, enter the zip code from the list.
for zip in zipcode:
url4 = url1+str(zip)+url2
Second part is not working
for x in range (0,75):
counter = x * 5
startdate += datetime.timedelta(days=counter)
enddate += datetime.timedelta(days=counter)
url = url4+startdate+","+enddate+url3
apifunction(url)
system said:
Traceback (most recent call last):
File "<pyshell#51>", line 3, in <module>
startdate += datetime.timedelta(days=counter)
AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'
Probably you're importing like this
from datetime import datetime
This way you import datetime type from datetime module. And this type of course does not have timedelta type in it.
You should import like this:
import datetime
In this case you simply import datetime module, and when you do datetime.timedelta it means that you want to use type timedelta from module datetime
It looks like datetime is getting redefined somewhere else in your code.
>>> import datetime
>>> type(datetime)
<type 'module'>
Your 'datetime' there is an object, which probably means you made a variable and called it datetime somewhere else in your code.

Categories

Resources