Python: Split Timestamp By Date And Hour
I have a list of timestamps in the following format: 1/1/2013 3:30 I began to learn python some weeks ago and I have no idea how to split the date and time. Can anyone of you hel
Solution 1:
I think that all you need is str.split
...
>>> s = '1/1/2013 3:30'>>> s.split()
['1/1/2013', '3:30']
If it's in a list, you can do with a list-comprehension:
>>> lst = ['1/1/2013 3:30', '1/2/2013 3:30']
>>> [s.split() for s in lst]
[['1/1/2013', '3:30'], ['1/2/2013', '3:30']]
Solution 2:
If you want to use this date and time further in your code to perform operations on this data such as comparing dates, you can convert this timestamp to datetime objects. Refer the documentation on datetime module.
You can use the following code to convert your timestamp to datetime object.
>>>import datetime>>>timestamp = datetime.datetime.strptime("1/1/2013 3:30", "%d/%m/%y %H:%M")>>>timestamp
datetime.datetime(2013, 1, 1, 3, 30)
>>>timestamp.date()
datetime.date(2013, 1, 1)
>>>timestamp.time()
datetime.time(3, 30)
If you just want to strip date and time to use them as strings, use method suggested by mgilson.
Solution 3:
Here is pseudocode to accomplish what you had mentioned in your comment:
f = file("path/to/file.csv", "r")
timestamp_column =10
def get_updated_row(i, row):
row= row.split(',')
try:
timestamp= row.pop(timestamp_column) #remove column
if i ==0:
#header
row.extend(["date", "time"]) #add columns
else:
#normal rowdate=timestamp[0]
time=timestamp[1]
row.extend([date, time])
except IndexError:
print("ERROR: Unable to parse row {0}".format(i))
return','.join(row)
with f.read() as csv:
for i, rowin enumerate(csv):
print(get_updated_row(i, row)) #write to file here instead if necessary
Post a Comment for "Python: Split Timestamp By Date And Hour"