Search code examples
pythonparsingpython-datetime

Parsing the string representation of struct_time


The data I am pulling from a database has string representations of time.struct_time.

Example for this string representation:

time.struct_time(tm_year=2022, tm_mon=1, tm_mday=9, tm_hour=19, tm_min=26, tm_sec=4, tm_wday=6, tm_yday=9, tm_isdst=0)

I would like to parse this string so that I can use it as a date object.

I have tried dateparser.parse and eval but no joy. I am reluctant to manually split it and parse it that way.

Is there a better way?


Solution

  • Ok, so i have a solution of sorts by using split and striptime

    I had just thought that there would perhaps be a way of using some kind of eval -like solution

    from datetime import datetime
    t = "time.struct_time(tm_year=2022, tm_mon=1, tm_mday=9, tm_hour=19, tm_min=26, tm_sec=4, tm_wday=6, tm_yday=9, tm_isdst=0)"
    t = t.split(', tm_wday=')[0]
    t = datetime.strptime(t, "time.struct_time(tm_year=%Y, tm_mon=%m, tm_mday=%d, tm_hour=%H, tm_min=%M, tm_sec=%S")
    t
    >> datetime.datetime(2022, 1, 9, 19, 26, 4)