-2

I have python returning a table of 2 columns the first column is name, second column in date formatted like this: 20150716170118. JavaScript is appending this data. I want to format the date to show something like this: Fri,17 2015 17:01:18.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97

2 Answers2

1

Use the datetime module and its strptime and strftime functions.

>>> import datetime
>>> thetime = '20150716170118'
>>> parsed_time = datetime.datetime.strptime(thetime, '%Y%m%d%H%M%S')
>>> formatted_time = datetime.datetime.strftime(parsed_time, '%a, %m/%d %Y %H:%M:%S')
>>> formatted_time
'Thu, 07/16 2015 17:01:18'
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • your's is an elegant solution just with std. library. Great. Didn't thought of using `strftime` again on `strptime`. – Tanmaya Meher Jul 17 '15 at 20:07
  • I understand all that and I used the strptime and strftime with no issues before. This time I'm querying a database and outputting the result into a webpage. Thanks for your time – syntax_error Jul 17 '15 at 20:09
  • Then you'll have to be more specific about what you're actually trying to do. – TigerhawkT3 Jul 17 '15 at 20:12
  • @MAM as per your question, your 2nd col. is date. **1.** So retrieve data from that column using python and the db. **2.** use the retrieved date and convert into formatted one. **3.** Then write it into your webpage (i don't know what you are using for this one). But what is the link between step 2 and step 1 and 3!? There should be no problem. – Tanmaya Meher Jul 17 '15 at 20:20
0
import dateutil.parser as dp
dp.parse('20150716170118').strftime("%a, %m %Y %H:%M:%S")

You need to install dateutil module for that. use pip install python-dateutil

Tanmaya Meher
  • 1,438
  • 2
  • 16
  • 27