Search code examples
pythondatetimeunicodepython-unicode

How to create datetime object from a unicode string?


I am haviing trouble converting in python from this format:

u'08:00:00' 

to a datetime object like:

datetime.datetime(2017,02,22,8,0,0)

What is an easy way to do this?

I can do it by just parsing the string but looking for more elegant solution


Solution

  • First you need to parse the time string. You can do that by hand, or use datetime.strptime():

    from datetime import datetime
    
    s = u'08:00:00'
    t = datetime.strptime(s, '%H:%M:%S').time()
    

    strptime() doesn't care that you give it a unicode string. That will give you a datetime.time object:

    >>> t
    datetime.time(8, 0)
    

    Then use datetime.combine() to combine the time with today's date:

    from datetime import date
    
    dt = datetime.combine(date.today(), t)
    

    This will give you the required datetime.datetime object:

    >>> dt
    datetime.datetime(2017, 2, 24, 8, 0)