简体   繁体   中英

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 ?

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'

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

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM