I'm calling an api and getting the datetime field in this format /Date(1500462505221)/ . My motive is to convert it to this format "2018-05-11 23:25:47" . How do I accomplish this ?
Asked
Active
Viewed 1.8k times
3 Answers
6
You can use datetime library to make life simple:
from datetime import datetime
datetime.fromtimestamp(1485714600).strftime("%Y-%m-%d %I:%M:%S")
-
I forgot to mention. Is it possible without doing any string operations ? Any library that takes the string as is and converts to datetime ? – Nilesh Kumar Guria Jul 03 '18 at 13:52
-
can you give me one example of string which you want to convert in datetime? – kanishk Jul 03 '18 at 13:59
-
'/Date(1506342842815)/' – Nilesh Kumar Guria Jul 03 '18 at 14:02
-
import time time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1506342842815/1000.)) – kanishk Jul 03 '18 at 18:17
-
So basically I would need to trim off "/Date(" and ")/" ? – Nilesh Kumar Guria Jul 04 '18 at 10:42
-
Why you need to trim, you directly give number rather than '/Date(1506342842815)/'. – kanishk Jul 04 '18 at 13:18
1
So here is what i got to convert time in human readable format, maybe this can help:
import time
time.strftime("%a, %d %b %Y %H:%M:%S %Z", time.localtime(1500462505221))
or
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1500462505221))
and one more thing i tried this example by removing last three digit of as follows and got this as output:
>>time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1500462505))
>>'2017-07-19 11:08:25'
You can also refer this link: [https://www.systutorials.com/241698/how-to-convert-epoch-timestamp-to-human-readable-date-format-in-python/

Deepak Verma
- 617
- 5
- 18
-
Is there any solution without doing any string manipulation/modifications ? – Nilesh Kumar Guria Jul 03 '18 at 13:51
-
i tried it without any string modification but that's not working fine. In fact trimming the string would be a good option. – Deepak Verma Jul 04 '18 at 11:38
1
You can do something like this using time
and re
modules:
import re, time
epoch_str = "/Date(1500462505221)/"
date = re.match(r'/Date\((\d+)\)/', epoch_str).groups()[0]
epoch_fmt = time.strftime('%Y-%M-%d %H:%M:%S', time.gmtime(float(date)))
# Or you can do
# date_ = time.gmtime(float(date))
# epoch_fmt = '{}-{}-{} {}:{}:{}'.format(date_.tm_year, date_.tm_mon, date_.tm_mday, date_.tm_hour, date_.tm_min, date_.tm_sec)
print(epoch_fmt)
# 49517-20-07 04:20:21

Chiheb Nexus
- 9,104
- 4
- 30
- 43