44904

How to parse JSON datetime string in python?

Question:

From python I am making a call to a remote API which returns data in a JSON format. I then parse the data using the json module with json.loads(). The problem I am having is with dates - the system I am calling returns the date formatted like the following:

/Date(1354011247940+0000)/

which json.parse just parses out as a string. How can I convert this to a python date time object?

Edit: unlike <a href="https://stackoverflow.com/questions/8362312/convert-json-to-python-object-how-to-handle-datetime-conversion" rel="nofollow">Convert JSON to Python object: how to handle DateTime conversion?</a>, I have no control over the data being sent, so I can not simply change the format prior to serializing.

Answer1:

You should get unix timestamp with a regex from this date, then use datetime module to convert it to readable format:

>m = re.search(r"Date\((\d+)\+", 'Date(1354011247940+0000)') >print(datetime.datetime.fromtimestamp(int(m.group(1))/1000.0).strftime('%Y-%m-%d %H:%M:%S')) 2012-11-27 12:14:07

UPD: note , that you also have milliseconds in this date, they will be truncated by this code

Answer2:

Have you checked <a href="https://stackoverflow.com/questions/8362312/convert-json-to-python-object-how-to-handle-datetime-conversion" rel="nofollow">Convert JSON to Python object: how to handle DateTime conversion?</a>?

This looks very similar - and an alternative way to what moonsly provided, although, I think moonsly has provided a more 'pythonic' approach than what is provided in the other similar thread (IMO)

Answer3:

I couldn't add this to the comments of moonsly's answer (no rep), so I made it a separate answer. Just wanted to add a few things others may find useful. I had this same issue but the json dates were appearing in my data a little differently (ie no + sign):

/Date(1416458650000)/

There are 9 or 13 character strings. The 9 char strings don't need to be divided by 1000.0. I also didn't use regex to extract the time string.

MILLISECONDS = '/Date(1416458650000)/'.split('(')[1][:-2] print datetime.datetime.fromtimestamp(int(MILLISECONDS)/1000.0).strftime('%Y-%m-%d %H:%M:%S') 2014-11-20 15:44:10

I can also do

SECONDS = '/Date(1416458650000)/'.split('(')[1][:-5] print datetime.datetime.fromtimestamp(float(SECONDS)).strftime('%Y-%m-%d %H:%M:%S') 2014-11-20 15:44:10

Recommend

  • RavenDB indexing errors
  • how to solve invalid conversion specifier warning in iphone app
  • import scipy.sparse failed
  • Doctrine/Symfony entity generator and generating entity from one table
  • abstracting over a collection
  • Casting between Interfaces and Classes
  • jwtBearer bearer token with rc-1 update to ASP.Net 5
  • Enabling DTD support in Sql Server
  • During installation of Django, why do I keep getting ImportError: No module named django?
  • Convert SQLite database to XML
  • where do I find the xml.dom python package for the python-2.6.0-8.9.28 and I have a suse/x86_64 vers
  • Python pickle not one-to-one: different pickles give same object
  • SAXReader not re-ecape characters
  • WPF Visiblity Binding to Boolean Expression with multiple Variables
  • Conversion from string “a” to type 'Boolean' is not valid
  • ActiveRecord query for a count of new users by day
  • Django rest serializer Breaks when data exists
  • How to rebase a series of branches?
  • Illegal mix of collations for operation for date/time comparison
  • Azure Cloud Service Web Role web pages do not load
  • Fetching methods from BroadcastReceiver to update UI
  • Does CUDA 5 support STL or THRUST inside the device code?
  • Symfony2: How to get request parameter
  • what is the difference between the asp.net mvc application and asp.net web application
  • Akka Routing: Reply's send to router ends up as dead letters
  • GridView Sorting works once only
  • AT Commands to Send SMS not working in Windows 8.1
  • Arrays break string types in Julia
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • WPF Applying a trigger on binding failure
  • How do I configure my settings file to work with unit tests?
  • Can Visual Studio XAML designer handle font family names with spaces as a resource?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • apache spark aggregate function using min value
  • How can I remove ASP.NET Designer.cs files?
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • Is it possible to post an object from jquery to bottle.py?
  • Sorting a 2D array using the second column C++
  • How can I use threading to 'tick' a timer to be accessed by other threads?