I need to retrieve datetime info from Google Calendar API. I am looking into this quickstart example. It retrieves start time of the meeting in a string format.
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
print(start, event['summary'])
How can I retrieve the time in datetime format, not in a string format. So I can extract out year, month, hour, minute etc. information.
EDIT: An example output from the above statement
2018-03-07T13:00:00-08:00
How about using dateutil? I think that there may be other methods. So please think of this as one of them.
Modified script :
import dateutil.parser
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
parsedDate = dateutil.parser.parse(start)
print(parsedDate, event['summary'])
Reference :
dateutil
If I misunderstand your question, I'm sorry.
Related
I'm recieving date in PMS message something like this |GA090616|GD090617|
which means Guest Arrival is at 09-06-16 and Guest Deprature is at 09-06-17
I wanted to parse it as date using python.
I've also visited stack oveflow[1, 2 ...] for this but as solution I've found
from datetime import datetime
self.DATE_FROMAT='%d/%m/%y'
arrival_date=datetime.strptime('90616', self.DATE_FROMAT).date()
print(arrival_date)
and it's not possible to parse it like this due to its unclear format.
I'm not sure if 09 is a month or a date, but from what I've seen in documents and PDFs, it appears to be a month.
Is there any better solution for this kind of date parsing? or suggestions for my expectations.
09-06-16,
09-06-17
Note:
Please Just take the date from the string 090617 and parse it as a date. That will be helpful.
You can do this with regex matching, you can either split the string with msg.split("|") or not, but that depends on your use case.
import re
from datetime import datetime
msg = "GA090616|GD090617|"
DATE_FORMAT='%d%m%y'
ar = re.match("GA(\d{6})", msg)
dp = re.match("GD(\d{6})", msg)
guest_arrival = datetime.strptime(ar.group(1), DATE_FORMAT).date()
guest_departure = datetime.strptime(dp.group(1), DATE_FORMAT).date()
Although not fully tested, this should be a boilerplate as to how to retrieve the date from the message. Remember to remove the \ from the date format, as that is not included in the message.
I am trying to figure out a clever way to take a user's input and store it in a database to be retrieved at a later date.
For context, this is a Discord bot where I am trying to track users' schedules. The idea is that the user could say "&addtime 12/30/1 12pm CST" and the bot would record that they will be online at 12/30/1/ at 12pm CST
The reason I want to track the timezone is so I can convert all the timezones to a specific timezone so that timezones wont get confused.
So after someone adds their time above, if I (someone PST), goes to retrieve when people will be online, I can type "&schedules PST" and get all of the times in the specified timezone.
The problem I'm facing now is all of the datetime examples I can find online all take very exact and specific input. I'm looking for a more forgiving function that is smart enough to figure out datetimes.
Figured it out with this method. it only supports US timezones, but that was enough for my needs:
from dateutil import parser
from dateutil import tz
import pytz
def parse_date(self, msg):
ET = tz.gettz('US/Eastern')
CT = tz.gettz('US/Central')
MT = tz.gettz('US/Mountain')
PT = tz.gettz('US/Pacific')
us_tzinfos = {'CST': CT, 'CDT': CT,
'EST': ET, 'EDT': ET,
'MST': MT, 'MDT': MT,
'PST': PT, 'PDT': PT}
usertime = parser.parse(msg, tzinfos=us_tzinfos)
servertime = usertime.astimezone(pytz.timezone("America/Phoenix"))
parse_date("12/30/20 12pm EST")
How do I show or output string in Python depending on what day it is, say I want a quote for today shown today and another quote tomorrow.
Something like if date == today’s date print(“quote”) and so on?
It’s for my app, like you access the app, click the button and it shows you today’s quote, and tomorrow the same but a different quote?
If all you want is to print the current date you could use the following
from datetime import date
today = date.today()
print(today)
all this does is store the date of today in "today"
For the day of posting printing today gives you 2020-02-07
Hope this helps.
I am working with pyExchange on windows 7 machine. I have a simple python v2.7 script that retrieves the Outlook calendar events from the exchange server. The script is provided below:
Code:
from pyexchange import Exchange2010Service, ExchangeNTLMAuthConnection
from datetime import datetime
import time
from pytz import timezone
def getEvents():
URL = u'https://xxxxx.de/EWS/Exchange.asmx'
USERNAME = u'MS.LOCAL\\xxxxx'
PASSWORD = u"xxxxxx"
connection = ExchangeNTLMAuthConnection(url=URL,
username=USERNAME,
password=PASSWORD)
service = Exchange2010Service(connection)
timestamp = datetime.now()
print timestamp.strftime('%Y, %m, %d, %H, %M, %S')
print time.timezone
eventsList = service.calendar().list_events(
start=timezone("Europe/Amsterdam").localize(datetime(2015, 1, 19, 0, 0, 0)),
end=timezone("Europe/Amsterdam").localize(datetime(2015, 1, 19, 23, 59, 59)),
details=True
)
for event in eventsList.events:
print "{start} {stop} - {subject} - {room}".format(
start=event.start,
stop=event.end,
subject=event.subject,
room=event.location
)
getEvents()
Problem:
The timestamp of the events doesn't match the timestamp of the events in Outlook. I created the events manually using the Outlook as well as using a pyExchange script.
For eg: If I create an event from 11:00 AM - 11:30 AM in Outlook, then the above script will return the timestamp of that event as 10:00 AM - 10:30 AM. The time is one hour less/back.
If I check my time.timezone it returns W. Europe Standard Time. I have specified my timezone in the script too ie. Europe/Amsterdam. But still the problem persists. Also I checked the timezone settings in Outlook. Shown below:
I logged into the Exchange server and it is also in the same timezone as my client machine.
Any suggestion regarding why the time is not correct for the events? Is this a bug in pyExchange? I would really appreciate it, if some one can test this and report back here, just to be sure that its not only me who is facing this issue.
I looked and it's probably not a bug in pyexchange, but how you're handling timezones. No shame, they're sadly extremely confusing in Python.
First, the package is returning event dates in UTC and not your local time. You're seeing an hour off the expected time because your timezone is +1 UTC. Here's an event I pulled from my calendar using your script (this is start/end/name/room):
2015-01-19 20:00:00+00:00 2015-01-19 21:00:00+00:00 - Lunch - Cafe
Note the +00:00 - that means it's in UTC. Noon here in California is 20:00 UTC.
Always, always, use UTC when handling datetimes. Here's some doc from the pytz folk on why localtimes are dangerous.
PyExchange tries to have your back and will convert localtime to UTC, but it always returns UTC. That's on purpose because see the previous link.
Now, to answer your question on getting this to work. First, convert your local time to UTC using these handy tips:
Use datetime.now(pytz.utc) to get the current datetime
Don't use datetime(…, tzinfo=timezone) to create a timezone aware datetime object, it's broken. Instead, create the datetime object and call timezone.localize on it.
For you, that means you have to do ugly stuff like:
start = timezone("Europe/Amsterdam").localize(datetime(2015, 1, 19, 0, 0, 0))
start = start.astimezone(pytz.utc)
Then, when you want to display UTC dates as your own time, do:
event.start.astimezone(timezone("Europe/Amsterdam"))
When I do that, I see this output from your script:
2015-01-19 21:00:00+01:00 2015-01-19 22:00:00+01:00 - Lunch - Cafe
which I would expect. Noon my time is 9pm your time.
Here's a gist of your script that I changed. Take a look and see if it fixes your problem. If not, I'm happy to look again!
my requirement is to display tweets of particular time period using twitter api. I am using getsearch method of api to get all tweets i have tried the following code to display tweets of particular time period.
Three_days_ago = datetime.datetime.utcnow()-datetime.timedelta(days = 3)
for tweet in tweets:
if tweet.created_at > Three_days_ago:
print tweet
but i am getting error 'can't compare datetime.datetime to unicode'
How to do this please suggest me..
You can use dateutil.
from dateutil import parser
Three_days_ago = datetime.datetime.utcnow()-datetime.timedelta(days = 3)
for tweet in tweets:
tweeted_datetime = parser.parse(tweet.created_at)
if tweeted_datetime > Three_days_ago:
print tweet, tweeted_datetime.strftime("%Y-%m-%d %H:%M:%S %p")
I'm not sure that you'll be able to get the milliseconds as it's not passed while parsing. For more strftime options refer here.
As #jamylak says, tweet.created_at is text not a datetime.
You can convert it to a datetime according to the rules given here: http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior