Pari Ganjoo
Pari Ganjoo

Reputation: 15

converting a date to list in python

I want to convert a date to a list format and then access its elements. The current code I am using is -

 start = str(start)
 start = list(start.split("-"))
 print(start)

where start will be a date in the format - MM/YYYY/DD

But the output for this is -

['0.0019821605550049554']

I don't understand what am I doing wrong

Upvotes: 0

Views: 439

Answers (4)

Franklin Moux
Franklin Moux

Reputation: 11

This is a simple answer to what you are asking for. Make sure to state the date as a string so that the numbers would not divide each other!

start ="5/2009/30"

start = list(start.split("/"))

print(start)

Upvotes: 1

raghu
raghu

Reputation: 355

 start = list(start.split("-"))

This looks for "-". If your format has "/" please use

    start = list(start.split("/"))

But as given in the comment How to get current time in python and break up into year, month, day, hour, minute? is better

Upvotes: 0

Boolean
Boolean

Reputation: 25

According to the output you are getting, this is how your code must be -

    start = 5-2009-30
    start = str(start)
    start = list(start.split("-"))
    print(start)

What your code is doing, is that, it subtracts 5, 2009, and 30. Because the values you gave in that variable are integral, and the "-" symbol means subtraction, it divides the numbers. Then It is converting the answer into a string, then converting into a list, and printing the difference. That is why you are getting the wrong output. You can avoid this by, placing the data between the quotating marks. Converting into string means that, it just converts the answer into a string, thats why even when you typed the str() function, it didnt give any result

So your final code should be -

start = "5-2009-30"
start = list(start.split("-"))
print(start)

Upvotes: 0

akime
akime

Reputation: 85

I think the problem is that you possibly have the / outside of a string, which is giving you a the month divided by year divided by day, maybe check to see if the start variable was a string to begin with? as once the math is done converting it to a string will only convert the result, not the string itself. see here:

start = 8/1986/20
start = str(start)
start = list(start.split("-"))
print(start)

When the date is not enclosed in quotations, it treats it as an equation and returns:

#['0.0002014098690835851']

when it is in quotations it works, but your split is not correct

start = '8/1986/20'
start = str(start)
start = list(start.split("-"))
print(start)

it returns

#['8/1986/20']

what you want is

start = '8/1986/20'
start = str(start)
start = list(start.split("/"))
print(start)

which returns:

#['8', '1986', '20']

Upvotes: 4

Related Questions