Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse FB Graph API date string into python datetime

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.

like image 993
DMac the Destroyer Avatar asked Aug 22 '11 02:08

DMac the Destroyer


People also ask

How do I convert a string to a datetime in Python?

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.

How do you parse a date format in Python?

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.

How do you convert date to month and year in Python?

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.

What is Graph API Facebook?

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.


2 Answers

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:

  • %Y = year with century (2011)
  • %m = month w/ leading zero
  • %d = day w/ leading zero
  • %H = hour w/ leading zero, 24-hour clock
  • %M = minute
  • %S = second
  • T, -, and : are used as delimiters, and included as literal strings
  • +0000 is again included as a literal string
like image 144
shelhamer Avatar answered Nov 07 '22 00:11

shelhamer


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)
like image 40
timger Avatar answered Nov 06 '22 22:11

timger