How to format time in ISO 8601 in Twilio API - python

I'm trying to use Twilio's messaging services to schedule a text, but I can't figure out how to format the time properly. I've pretty much copied the instructions to a T from Twilio's website, but I keep getting an invalid syntax error. Here's the line of code for the send_at variable:
send_at=datetime(2022-2-8'T'17:50:00'Z'),
How do I format this properly so it'll run? Thanks in advance for the help.

How is this timestamp being generated? Are you hard-coding it? The syntax error you're seeing is Python being unable to understand what's in between the parentheses, it doesn't seem syntactically correct.
You could simply use the isoformat() method from Python's datetime library instead to convert a regular datetime object to ISO afterwards, example:
>>> import datetime
>>> x = datetime.datetime(2022, 2, 8, 17, 50)
>>> x.isoformat()
'2022-02-08T17:50:00'
Twilio's own docs directly suggest this pattern (see the "Send Scheduled SMS in Python" section):
message = client.messages.create(
from_=messaging_service_sid,
to='+1xxxxxxxxxx', # ← your phone number here
body='Friendly reminder that you have an appointment with us next week.',
schedule_type='fixed',
send_at=send_when.isoformat() + 'Z',
)
Looks like the only additional detail is appending that 'Z' at the end, which is the only difference between my first snippet and your original example. If there are different docs that you followed that you can share a link to, happy to give more specific advice.

Related

How to retrieve strptime model with string and datetime object available?

Suppose I have a large set of strings I want to parse to a set of datetime objects. I could use the dateutils.parser and iterate through the set but it is more computer intensive and takes a longer time than parsing one, retrieving the strptime format applied and just do datetime.strptime(string, model).
I wanted to create a function, a bit like the following:
def retrieve_format(datetime_object, string):
#do some things
return model
with the model being a string.
I have found nothing that explains the inner workings of the dateutils parser, and I believe the developers have the ability to add such a feature.
Any idea on how to do it ? It would save time and computing power.
Example
Suppose I have a set of string that are formatted the same way as this one:
myStr = '27/03/2020 - 16:20'
I could do
myDate = dateutils.parser.parse(myStr)
and get 'myDate' as being
datetime.datetime(2020, 3, 27, 16, 20)
but now I could use my function as such
>>> model = retrieve_format(myDate, myStr)
>>> print(model)
%d/%m/%Y - %H:%M
I could then do
datetime_set = {}
for formatted_string in set:
raw = datetime.datetime.strptime(formatted_string, model)
datetime_set.add(raw)
to treat all the other elements very efficiently.
Okay so thanks to snakecharmerb's comment on my question, I found this comment which uses the dateinfer library. Here, just the string is needed. Installation with pip is possible
pip install pydateinfer
A working example would be the following
import dateinfer
dateinfer.infer(['27/03/2020 - 16:20', '28/03/2020 - 14:56' ])
and the output is
'%d/%m/%Y - %H:%M'
The input is always a list, even if it contains only one element.
Depending on the ambiguity of the string, the list should have more or less elements. That is because for example in '04/04/2020', we have no means of distinguishing the day or the month.

Convert Instagram response device time stamp to readable date time

I'm using Instagram-API-python to create an application. I'm getting a JSON response with below value.
'device_timestamp': 607873890651
I tried to convert this value to readable using python.
import time
readable = time.ctime(607873890651)
print(readable)
It gives following result and seems it is not correct.
Sun Oct 3 16:00:51 21232
I'm not much familiar with the Instagram-API-python. Please someone can help me to solve this problem.
The data is very likely to be incorrect.
Timestamp is a very standard way to store a date-time. Counting the seconds that passed since January 1st, 1970, also known as the UNIX Epoch.
I looked for "Instagram 'device_timestamp'" on Google and all the user-provided values made sense, but yours doesn't.
This is probably an error from the database, it happens.
Use the mentioned ctime conversion, but take the 'taken_at' field if available.
Don't use device_timestamp but use taken_at field. Then taken_at need multiply to 1000.
In Java it looks like this
Date data = new Date(taken_at * 1000);

How to compare a google datastore datetime to python datetime?

I am trying to write a function in python that deletes entries in my datastore that are more than five minutes old. I'm making a kitten picture database for a class, so my code looks something like this:
class KittenImg(db.Model):
"""Models a Gallery entry with kitten_name, image, and date."""
kitten_name = db.StringProperty(multiline=True)
image = db.BlobProperty()
date = db.DateTimeProperty(auto_now_add=True)
A user uploads a KittenImg and it loads into the datastore and returns just fine, but I don't think I understand really what format a kitten.date value would return and how I can compare it to datetime.now() using Python. I have tried a few different options in the python datetime module documentation, but I just really don't think I have a good enough understanding of what I'm getting when I call datetime.now() and when I ask for a kitten.date.
I feel like after looking at the documentation for about three hours, I still have no idea how to even begin getting the solution.
I've been trying things like:
now = datetime.now()
then = kitten.date
tdelta = now - then
And:
now = total_seconds(datetime.now())
then = total_seconds(kitten.date)
tdelta = now - then
But in each case, it gives me an unauthorized operator for the - sign.
It seems like datetime.timedelta() should have something to do with it, but I have absolutely no idea how to use that function even after staring at it for hours.
Can someone please help me either:
1. Understand what's going on with the datetime module better or
2. Give me another way to approach my problem?
Thanks
Sorry, I answered my own question. I must have been doing something different last night, but I got it to work tonight. This is what I did:
for kitten in kittens:
then = kitten.date
now = datetime.datetime.now()
tdelta = now - then
if tdelta.total_seconds() > 300:
kitten.delete()
Should probably have put a static of FIVE_MIN instead of using the magic number 300, so forgive me for that, but it worked.

getting datetime from python string when tzinfo is present

I have found answers to question like this one helpful but not complete for my problem.
I have a form where the user automatically produces a date. I would like to store that as a date time.
I don't need any of the information after the seconds, but I cannot find a datetime.datetime.strptime code to translate the remaining stuff. So I would either like a strptime code that works for python2.7 on google app engine, or a string editing trick for removing the extra information that is not needed.
date-from-user='2012-09-22 07:36:36.333373-05:00'
You can slice your string to only select the first 19 characters:
>>> datefromuser='2012-09-22 07:36:36.333373-05:00'
>>> datefromuser[:19]
'2012-09-22 07:36:36'
This let's you parse the date without having to bother with the microseconds and timezone.
Do note that you probably do want to parse the timezone too though. You can use the iso8601 module to handle the whole format, without the need to slice:
>>> import iso8601
>>> iso8601.parse_date(datefromuser)
datetime.datetime(2012, 9, 22, 7, 36, 36, 333373, tzinfo=<FixedOffset '-05:00'>)
The iso8601 module is written in pure python and works without problems on the Google App Engine.
Python Docs would be a good place to start. strptime() would be your best option.
import datetime
datefromuser = '2012-09-22 07:36:36.333373-05:00'
datetime.datetime.strptime(datefromuser.split(".")[0], "%Y-%m-%d %H:%M:%S")
2012-09-22 07:36:36
http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior

Formatting date times provided as strings in Django

In my Django application I get times from a webservice, provided as a string, that I use in my templates:
{{date.string}}
This provides me with a date such as:
2009-06-11 17:02:09+0000
These are obviously a bit ugly, and I'd like to present them in a nice format to my users. Django has a great built in date formatter, which would do exactly what I wanted:
{{ value|date:"D d M Y" }}
However this expects the value to be provided as a date object, and not a string. So I can't format it using this. After searching here on StackOverflow pythons strptime seems to do what I want, but being fairly new to Python I was wondering if anyone could come up with an easier way of getting date formatting using strings, without having to resort to writing a whole new custom strptime template tag?
You're probably better off parsing the string received from the webservice in your view code, and then passing the datetime.date (or string) to the template for display. The spirit of Django templates is that very little coding work should be done there; they are for presentation only, and that's why they go out of their way to prevent you from writing Python code embedded in HTML.
Something like:
from datetime import datetime
from django.shortcuts import render_to_response
def my_view(request):
ws_date_as_string = ... get the webservice date
the_date = datetime.strptime(ws_date, "%Y-%m-%d %H:%M:%S+0000")
return render_to_response('my_template.html', {'date':the_date})
As Matthew points out, this drops the timezone. If you wish to preserve the offset from GMT, try using the excellent third-party dateutils library, which seamlessly handles parsing dates in multiple formats, with timezones, without having to provide a time format template like strptime.
This doesn't deal with the Django tag, but the strptime code is:
d = strptime("2009-06-11 17:02:09+0000", "%Y-%m-%d %H:%M:%S+0000")
Note that you're dropping the time zone info.

Categories