Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert weird Python date format to readable date

Tags:

python

date

I am using Python to access the mobile API of some web service and the response contains the following weird Date notation: u'/Date(1409522400000+0200)/' This should be the 1st of September, 2014.

I am not sure which format this is, but I would like to convert this to something readable, i.e. a date or a datetime or Unix time.

Can anybody help me with this?

like image 691
JNevens Avatar asked Feb 12 '15 16:02

JNevens


People also ask

How do I fix date format in Python?

Function usedstrftime() can change the date format in python.

How do you change date format to MM DD YYYY in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

How do I convert a date in Python?

For this, we will use the strptime() method and Pandas module. This method is used to create a DateTime object from a string. Then we will extract the date from the DateTime object using the date() function and dt. date from Pandas in Python.


2 Answers

The time string looks like OData version 2 JSON verbose format for Datetime that may be seen in old ASP.NET or WCF applications:

“/Date(<ticks>[“+” | “-” <offset>])/”
<ticks> = number of milliseconds since midnight Jan 1, 1970
<offset> = utc offset

#!/usr/bin/env python3
import re
from datetime import datetime, timedelta, timezone

time_string = u"/Date(1409522400000+0200)/"
epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
ticks, offset = re.match(r'/Date\((\d+)([+-]\d{4})?\)/$', time_string).groups()
utc_dt = epoch + timedelta(milliseconds=int(ticks))
print(utc_dt)
if offset:
   offset = int(offset)
   hours, minutes = divmod(abs(offset), 100)
   if offset < 0:
      hours, minutes = -hours, -minutes
   dt = utc_dt.astimezone(timezone(timedelta(hours=hours, minutes=minutes)))
   print(dt)

Output

2014-08-31 22:00:00+00:00
2014-09-01 00:00:00+02:00

where timezone is defined here.

like image 62
jfs Avatar answered Sep 29 '22 01:09

jfs


you received a (java?) timestamp in milliseconds. you can convert it to something more readable like so:

from datetime import date

d=1409522400000/1000.0 # divide by 1000 to get seconds
print date.fromtimestamp(d) # -> 2014-09-01
like image 26
kasper Taeymans Avatar answered Sep 29 '22 01:09

kasper Taeymans