Here's an example of how the Facebook Graph API is returning date strings for me:
2011-03-06T03:36:45+0000
how would I parse this into a python datetime class? I'm aware of the datetime.strptime function, which takes in a second parameter that contains some googly-eyed format string, but don't know which letters and dashes to include.
We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.
Python has a built-in method to parse dates, strptime . This example takes the string “2020–01–01 14:00” and parses it to a datetime object. The documentation for strptime provides a great overview of all format-string options.
In this article, we are going to convert DateTime string of the format 'yyyy-mm-dd' into DateTime using Python. yyyy-mm-dd stands for year-month-day . We can convert string format to datetime by using the strptime() function. We will use the '%Y/%m/%d' format to get the string to datetime.
The Graph API is the primary way to get data into and out of the Facebook platform. It's an HTTP-based API that apps can use to programmatically query data, post new stories, manage ads, upload photos, and perform a wide variety of other tasks.
Here it is with time & strptime:
>>> time.strptime('2011-03-06T03:36:45+0000', '%Y-%m-%dT%H:%M:%S+0000')
time.struct_time(tm_year=2011, tm_mon=3, tm_mday=6, tm_hour=3, tm_min=36, tm_sec=45, tm_wday=6, tm_yday=65, tm_isdst=-1)
or with datetime:
>>> datetime.datetime.strptime('2011-03-06T03:36:45+0000','%Y-%m-%dT%H:%M:%S+0000')
As you see it returns the time_struct with the fields correctly filled out.
Here is a translation of the format:
In [10]: datetime.datetime.strptime('2011-03-06T03:36:45+0000','%Y-%m-%dT%H:%M:%S+0000')
Out[10]: datetime.datetime(2011, 3, 6, 3, 36, 45)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With