cambiar (por ejemplo) 8 a 08 ... python

I am reading data from a csv file, and there are date elements in it, but there is an inconsistency in the dates.

For example: sometimes the date element is like 1/1/2011 and sometimes it is like 01/01/2011

Since I am plotting this data later.. this causes a great deal of noise in my plots. The following is my date class. Can you help me out in where and how to modify the code in order to get the date in the form 01/01/2011

import re
class Date:
def __init__(self, input_date):
    self._input_date = input_date
    self._date = None
    self._month = None
    self._year = None
    self._hour = None
    self._min = None


def  setDate(self):
    date = self._input_date
    #date = re.findall('w+',date)
    date = self.__mySplit()
    #print"len ",len(date)
    assert (len(date) >= 3) #has atleast dd/mm/yy 
    #dateLength = len(date[0])

    self._month = int(date[0])
    self._date = int(date[1])
    self._year = int(date[2])
    if (len(date) ==5):
        self._hour = int(date[3])
        self._min = int(date[4])

def __mySplit(self): #splitting the date by delimiters..
    res = [self._input_date]
    #print res
    seps = [' ','/',':']
    for sep in seps:
        s,res = res,[]
        for seq in s:
            res += seq.split(sep)
            #print res
    return res

Muchas Gracias

preguntado el 08 de noviembre de 11 a las 18:11

1 Respuestas

You definitely want to be using datetime. Here's some code that will get a datetime from either string type:

from datetime import datetime

def strToDatetime(dateStr):
    return datetime.strptime(dateStr, "%d/%m/%Y")

Then, you can print a datetime out in the format you want with:

strToDatetime("1/3/2011").strftime("%d/%m/%Y)
>'01/03/2011'

You should never need to roll your own date/time/datetime structure in python.

respondido 08 nov., 11:22

What Aaron said. Use the built in tools for this. - Peter Loron

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.