Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date String to Time tuple

I am trying to pass a string into as function and need to convert it into a time tuple:

def  sim(startdate, enddate):
    # need to convert the date from string to integer time tuple:
    dt_start = dt.date(startdate)
    print 'Start Date: ', dt_start

    dt_end = dt.date(enddate)
    print 'End Date: ', dt_end

# in String format
sim('Jan 1, 2011', 'Dec 31, 2011')

# in interger in string format
sim('2011,1,1', '2011,12,31')
like image 447
pythonhunter Avatar asked Nov 19 '25 21:11

pythonhunter


2 Answers

Another way would be to use strptime(). Have a time format defined for both of your formats and use them accordingly. This is what I mean:

import datetime as dt

def  sim(startdate, enddate):
    time_format_one = "%b %d, %Y"
    time_format_two = "%Y,%m,%d"

    try:
        dt_start = dt.datetime.strptime(startdate, time_format_one)
        dt_end = dt.datetime.strptime(enddate, time_format_one)
    except ValueError:
        dt_start = dt.datetime.strptime(startdate, time_format_two)
        dt_end = dt.datetime.strptime(enddate, time_format_two)

    print 'Start Date: ', dt_start.date()
    print 'End Date: ', dt_end.date()

# in String format
sim('Jan 1, 2011', 'Dec 31, 2011')

# in interger in string format
sim('2011,1,1', '2011,12,31')

prints:

Start Date:  2011-01-01
End Date:  2011-12-31
Start Date:  2011-01-01
End Date:  2011-12-31

You could use timetuple() on dt_start and dt_end if you need time tuple.

like image 157
shaktimaan Avatar answered Nov 22 '25 11:11

shaktimaan


I assume you want to convert date ('Jan 1, 2011', 'Dec 31, 2011') and ('2011,1,1', '2011,12,31') into timetuple

 from datetime import datetime
 date_str = "Jan 1, 2011"
 fmt = "%b %d, %Y"

 # Construct a datetime object
 date_obj = datetime.strptime(date_str, fmt)

 # Convert it to any string format you want
 new_fmt = "%Y, %m, %d"
 print date_obj.strftime(new_fmt)
 # Prints'2011, 01, 01'

 # If you want python timetuple then
 t_tuple = date_obj.timetuple()
like image 39
siu Avatar answered Nov 22 '25 10:11

siu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!