mk_sch
mk_sch

Reputation: 1070

How to convert JSON date to the a special format in Python?

I am parsing a JSON file in Python 2.7 that includes

"TimestampUtc":"\/Date(1477393888000)\/

and I want to parse this file and convert the date into :

8:11 a.m. Oct. 25, 2016

The original time zone is in the US and I want to get exactly the same output. But this format is not that common and other similar questions don't answer it. Is there any idea how to do it ?

Upvotes: 5

Views: 11595

Answers (3)

Harsha Biyani
Harsha Biyani

Reputation: 7268

you can try:

>>> from datetime import datetime
>>> d = "1467717221000"
>>> d = int(d[:10])
>>> datetime.fromtimestamp(d).strftime('%Y-%m-%d %I:%M:%S %p')
'2016-07-05 04:43:41 PM'

edit: Format update :

>>> datetime.fromtimestamp(d).strftime(' %I:%M %p %b. %d, %y').replace("PM","p.m.").replace("AM","a.m.")
' 04:43 p.m. 07. 05, 16'

Upvotes: 9

solideo
solideo

Reputation: 127

This:

import datetime
import re


TimestampUtc = "\/Date(1467717221000)\/"

TimestampUtc = re.split('\(|\)', TimestampUtc)[1][:10]
date = datetime.datetime.fromtimestamp(int(TimestampUtc))
print date
print date.strftime('%I:%M %p %b. %d, %Y')
print date.strftime('%I:%M %p %b. %d, %Y').replace('AM', 'a.m.').replace('PM', 'p.m.')

Output:

2016-07-05 19:13:41
07:13 PM Jul. 05, 2016
07:13 p.m. Jul. 05, 2016

Upvotes: 3

Hulk
Hulk

Reputation: 271

I think the unit of your timestamp is milli seconds. So divide it into 1000 then you get 1467717221. And using date time module for get the time. Then convert it to your format by strftime.

from datetime import datetime

newTimeString = datetime.utcfromtimestamp(1467717221).strftime('%I:%M %p %b. %d, %Y')

you can find formatting from here(https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior)

Upvotes: 0

Related Questions