3

I have some data in a text file in the following format:

50 Cent     1975-07-06
75 Cents    1933-01-29
9th Wonder  1975-01-15
A Fine Frenzy   1984-12-23

I want to convert it as like:

50 Cent     July 6, 1975
75 Cents    January 29, 1933
9th Wonder  January 15, 1975
A Fine Frenzy   December 23, 1984

Could any of you please help me.Thanks in advance!

3
  • @ Sentinel: No, it's part of DB data conversion.I am quite new in python, don't understand really what to do. Commented Jul 3, 2011 at 19:37
  • Read the data line by line, split each line at the right whitespace (rsplit()) and then convert the date using strptime() as suggested....this is the blueprint...the rest is up to you...come back if you have some code. Commented Jul 3, 2011 at 19:39
  • 4
    By the way: No need to convert a perfectly normal date format, that is the standard around the world. It's ISO 8601. Commented Jul 3, 2011 at 19:43

3 Answers 3

4
import time

text = """50 Cent     1975-07-06
75 Cents    1933-01-29
9th Wonder  1975-01-15
A Fine Frenzy   1984-12-23"""

for line in text.splitlines():
    dob = line.rsplit(None, 1)[-1]
    dob_new = time.strftime('%B %d, %Y', time.strptime(dob, '%Y-%m-%d'))

    print line.replace(dob, dob_new)

Result:

50 Cent     July 06, 1975
75 Cents    January 29, 1933
9th Wonder  January 15, 1975
A Fine Frenzy   December 23, 1984

Bonus:

A strftime cheatsheet

Sign up to request clarification or add additional context in comments.

Comments

3

You can use strftime and strptime from datetime module Please find below my sample code:

output = []
with open(filename, 'r') as f:
    for line in (l.strip() for l in f if l.strip()):
        data = line.split()
        output.append(line.replace(data[-1], datetime.strptime(data[-1],'%Y-%m-%d').strftime('%B %d, %Y')))

Comments

0

one way is to use time.strptime to parse and time.strftime to format. pydoc time for the documentation.

1 Comment

@Forhad Open your terminal / command prompt and type pydoc time. Alternatively, google "python date time conversion formatting"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.