Date conversion in python
开发者_JS百科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!
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
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')))
one way is to use time.strptime to parse and time.strftime to format. pydoc time
for the documentation.
精彩评论