简体   繁体   中英

Howto convert a string to a date format

Hi guys would appreciate some help. I'm analyzng a series (a set of columns) that has a date format like this:

'1060208'

The first three digits represent the year where the first digit, '1' exists for comparison purposes. in the case above, the year is 2006. the 4th and 5th digit represent the month and the rest represents the day. I want to convert these dates to something like this

106-02-08

So that i can use .groupby to sort per month or year. Here is my code so far

    class Data:
        def convertdate(self):
            self.dates.apply(lambda x:x[0:3] + '-' + x[3:5] + '-' + x [5:7])
        return self.dates

when I run this, I get the error:

    TypeError: 'int' object is not subscriptable

Can you please tell me what went wrong? Or can you suggest some alternative way to do this? Thank you so much.

Assumings that dates is a list of int, you can do:

input_dates = [1060208, 1060209]
input_dates_to_str = map(lambda x: str(x), input_dates)
output = list(map(lambda x: '-'.join([x[0:3], x[3:5], x[5:]]), input_dates_to_str))

Anyway, when working with dates I suggest you using datetime package.

Quick answer to your question: 1060208 is an integer, integers are not subscriptable, so you need to change it to a string.

Some other thoughts: Where is your data? Is this all in a pandas dataframe? If so why are you writing classes to convert your data? There are better/faster ways of doing it. Like convert your intgeger date to a string, get rid of the first digit, and convert it to datetime.

What does "where 1 is put for comparison purposes" mean? It could have been recorded that way but obviously a date and a flag (I assume it is some kind of flag) should not be represented in the same field. So why don't you put that 1 in a field of its own?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM