String to datetime for Google Calendar API - python

I've gotten some events data from a website and stored the dates and starting times as string variables in python. My aim is to iterate over a for loop and over each iteration, create and add a new event to a google calendar using the Google Calendar API. I've stored the date and start/end times for each event as string variables so theoretically I would have:
date='2019-11-01'
start_time='10:00am'
end_time='11:00am'
I'd gotten so far until I realised that the way one must format the date and start/end times for an event is as follows:
'dateTime': '2015-05-28T09:00:00-07:00'
where if I am not mistaken, the RHS is a datetime object rather than a string. At first I thought I'd try sticking all my strings together with a T in between the date and time out of desperation, but obviously that didn't work because the object isn't supposed to be a string. I was wondering if there was any way I could use the variables I've obtained to create a new google event, or whether I've reached a dead end?
Many thanks in advance.

To add an event using Google Calendar's API you need a start_date and an end_date as datetime objects.
The following code creates datetime objects with your strings.
If you print those timeobjects with isoformat. you will see the "T" that you mentioned.
import datetime
date='2019-11-01'
start_time='1:20am'
end_time='11:00pm'
start_date_str = date + start_time
end_date_str = date + end_time
start_date = datetime.datetime.strptime(start_date_str, '%Y-%m-%d%I:%M%p')
end_date = datetime.datetime.strptime(end_date_str, '%Y-%m-%d%I:%M%p')
print(start_date.isoformat())
print(end_date.isoformat())

Related

How to convert the format all the values in a date-time array?

This is my data :
dates = np.arange("2018-01-01", "2021-12-31", dtype="datetime64[D]")
I now want to convert from :
"2018-01-01" -> "Jan-01-2018" ["Monthname-day-year"] format
How to i do this ?
Is it possible to initialize this in the way we want to convert ?
Can i use something like:
for i in dates:
i = i.replace(i.month,i.strftime("%b"))
You can try this:
from datetime import datetime
dates = np.arange("2018-01-01", "2021-12-31", dtype="datetime64[D]")
result_dates = []
for date in dates.astype(datetime):
result_dates.append(date.strftime("%b-%d-%Y"))
But you will need to convert result dates as shown in the code
I feel compelled to elaborate on Silvio Mayolo's very relevant but ostensibly ignored comment above. Python stores a timestamp as structure (see How does Python store datetime internally? for more information) Hence, the DateTime does not as such have a 'format'. A format only becomes necessary when you want to print the date because you must first convert the timestamp to a string. Thus, you do NOT need to initialise any format. You only need to declare a format when the time comes to print the timestamp.
While you CAN store the date as a string in your dataframe index in a specific format, you CANNOT perform time related functions on it without first converting the string back to a time variable. ie current_time.hour will return an integer with the current hour if current_time is a datetime variable but will crash if it is a string formatted as a timestamp (such as "2023-01-15 17:23").
This is important to understand, because eventually you will need to manipulate the variables and need to understand whether you are working with a time or a string.

Using BigQuery SQL with Built-in Python Functions

I recently started using Google's BigQuery service, and their Python API, to query some large databases. I'm new to SQL, and the BigQuery documentation isn't incredibly helpful for what I'm doing.
Currently I'm looking through the reddit_comments database, and there's 'created_utc' tag that I'm trying to filter by. This created_utc field is in terms of Unix timestamps (i.e. November 1st, 12:00 AM is 1541030400)
I'd like to grab comments day by day (or between two Unix timestamps) but in a way that I'm iterating over each day. Something like:
from datetime import datetime, timedelta
start = datetime.fromtimestamp(1538352000)
end = datetime.fromtimestamp(1541030400)
time = start
while time < end:
print(time)
time = time + timedelta(days = 1)
Printing times here yield one like: 2018-09-30 20:00:00
However in order to query, I have to convert back to the Unix timestamp by invoking datetime's timestamp() function like time.timestamp()
The problem is, I'm trying to use the timestamp() function inside the query like so:
SELECT *
FROM 'fh-bigquery.reddit_comments.2018_10'
...
AND (created_utc >= curr_day.timestamp() AND created_utc <= next_day.timestamp())
however, it's throwing a BadRequest: 400 Function not found. Is there a way to use built-in Python functions in the way that I've described above? Or does there need to be some alternative?
Everything so far seems pretty intuitive, but it's weird that I can't find much helpful information on this specifically.
You should use BigQuery's Built-in functions
For example:
To get current timestamp - CURRENT_TIMESTAMP()
To get timestamp of start of current date - TIMESTAMP_TRUNC(CURRENT_TIMESTAMP(), DAY)
To get timestamp of start of next date - TIMESTAMP_TRUNC(TIMESTAMP_ADD(CURRENT_TIMESTAMP() , INTERVAL 1 DAY), DAY)
and so on
Also, to convert created_utc to TIMESTAMP type - you can use TIMESTAMP_SECONDS(created_utc)
You can see more about TIMESTAMP Functions

Python ical start time

Here is my problem, I'm using Icalendar on Python to parse data from 2 ical file and one excel file (xls).
Problem, when I try to get my calendar (using this):
for event in cal.walk('vevent'):
dates = event.get('dtstart')
location = event.get('location')
dates=dates.to_ical()
month=dates[4:6]
day=dates[6:8]
heures2=dates[9:11]
minut=dates[11:13]
sec=dates[13:15]
yearical=dates[0:4]
date2=day+"/"+month+"/"+yearical
summary = event.get('summary')
icaldebheur = heures2+":"+minut+":"+sec
The problem is that my ical file look like this:
Calendar
The only hour that the code give me are the 8H one and 13h30one (observed by doing a print icaldebheur), no matter the day, it never give me the one at 10H (or, if it happen the afternoon, it don't give me one at 15H).
It seem like it only give me 2 event per day.
Do you have an idea?
One thing you have to be aware of when dealing with iCalendar files is timezones.
If the date/time property value ends in Z, that means the time is
formatted in UTC time.
If the date/time property has a TZID
parameter, that means the date/time value is formatted in a specific
timezone.

Python: creating list of timestamps by minute

I am trying to figure out what the best way to create a list of timestamps in Python is, where the values for the items in the list increment by one minute. The timestamps would be by minute, and would be for the previous 24 hours. I need to create timestamps of the format "MM/dd/yyy HH:mm:ss" or to at least contain all of those measures. The timestamps will be an axis for a graph of data that I am collecting.
Calculating the times alone isn't too bad, as I could just get the current time, convert it to seconds, and change the value by one minute very easily. However, I am kind of stuck on figuring out the date aspect of it without having to do a lot of checking, which doesn't feel very Pythonic.
Is there an easier way to do this? For example, in JavaScript, you can get a Date() object, and simply subtract one minute from the value and JS will take care of figuring out if any of the other fields need to change and how they need to change.
datetime is the way to go, you might want to check out This Blog.
import datetime
import time
now = datetime.datetime.now()
print now
print now.ctime()
print now.isoformat()
print now.strftime("%Y%m%dT%H%M%S")
This would output
2003-08-05 21:36:11.590000
Tue Aug 5 21:36:11 2003
2003-08-05T21:36:11.590000
20030805T213611
You can also do subtraction with datetime and timedelta objects
now = datetime.datetime.now()
minute = timedelta(days=0,seconds=60,microseconds=0)
print now-minute
would output
2015-07-06 10:12:02.349574
You are looking for datetime and timedelta objects. See the docs.

Python: How to extract time date specific information from text/nltk_contrib timex.py bug

I am new to python. I am looking for ways to extract/tag the date & time specific information from text
e.g.
1.I will meet you tomorrow
2. I had sent it two weeks back
3. Waiting for you last half an hour
I had found timex from nltk_contrib, however found couple of problems with it
https://code.google.com/p/nltk/source/browse/trunk/nltk_contrib/nltk_contrib/timex.py
b. Not sure of the Date data type passed to ground(tagged_text, base_date)
c. It deals only with date i.e. granularity at day level. Cant find expression like next one hour etc.
Thank you for your help
b) The data type that you need to pass to ground(tagged_text, base_date) is an instance of the datetime.date class which you'd initialize using something like:
from datetime import date
base_date = date.today()

Categories

Resources