indigo
indigo

Reputation: 1137

How to reformat a timestamp in Python

I have some text below that needs to handled. The timestamp is currently listed and then the value. The format for the timestamp is yyyymmdd and I want to be able to alter it to yyyy-mm-dd or some other variation: yyyy/mm/dd, etc. I can't seem to find a string method that inserts characters into strings so I'm unsure of the best way to do go about this. Looking for efficiency here and general advice on slicing and dicing text in python. Thanks in advance!

19800101,0.76
19800102,0.00
19800103,0.51
19800104,0.00
19800105,1.52
19800106,2.54
19800107,0.00
19800108,0.00
19800109,0.00
19800110,0.76
19800111,0.25
19800112,0.00
19800113,6.10
19800114,0.00
19800115,0.00
19800116,2.03
19800117,0.00
19800118,0.00
19800119,0.25
19800120,0.25
19800121,0.00
19800122,0.00
19800123,0.00
19800124,0.00
19800125,0.00
19800126,0.00
19800127,0.00
19800128,0.00
19800129,0.00
19800130,7.11
19800131,0.25
19800201,.510
19800202,0.00
19800203,0.00
19800204,0.00

Upvotes: 1

Views: 5317

Answers (3)

Brendan Long
Brendan Long

Reputation: 54312

I'd do something like this:

#!/usr/bin/env python

from datetime import datetime

with open("stuff.txt", "r") as f:
    for line in f:
        # Remove initial or ending whitespace (like line endings)
        line = line.strip()

        # Split the timestamp and value
        raw_timestamp, value = line.split(",")

        # Make the timestamp an actual datetime object
        timestamp = datetime.strptime(raw_timestamp, "%Y%m%d")

        # Print the timestamp separated by -'s. Replace - with / or whatever.
        print("%s,%s" % (timestamp.strftime("%Y-%m-%d"), value))

This lets you import or print the timestamp using any format allowed by strftime.

Upvotes: 3

Strings are not mutable so inserting characters into strings won't work. Try this:

date = '19800131'
print '-'.join([date[:4],date[4:6],date[6:]])

Upvotes: 1

NullUserException
NullUserException

Reputation: 85478

general advice on slicing and dicing text in python

The slice operator:

str = '19800101,0.76'
print('{0}-{1}-{2}'.format(str[:4], str[4:6], str[6:]))

Read: strings (look for the part on slices), and string formatting.

Upvotes: 1

Related Questions