How can you convert a string with varying length to datetime

I have a list that has strings with Y-M-D (eg. 2010-01-14) format, but some don't have the month and/or the day. I've tried doing it based on the length but it became long and messy. Is there an easy way to accomplish this?

1 answer

  • answered 2021-09-27 13:21 MrFuppes

    does this satisfy your needs: dateutil's parser with a default date, Ex:

    from datetime import datetime
    from dateutil import parser
    for s in '2021', '2021-01', '2021-02-03':
        print(parser.parse(s, default=datetime(2021,1,1)))
    2021-01-01 00:00:00
    2021-01-01 00:00:00
    2021-02-03 00:00:00

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum