Search code examples
pythondatetimetimestampnanotime

How to convert a string to a DatetimeWithNanoseconds format with python?


I have multiples strings representing timestamps. A few examples may be : 19551231 (%Y%m%d) or 20210216154500 (%Y%m%d%H%M%S). As you can see, the format may vary.

I'm looking for a way to convert all these different strings to a unique DatetimeWithNanoseconds format.

I know I can convert a timestamp to DatetimeWithNanoseconds using integers like this: DatetimeWithNanoseconds(2020, 6, 22, 17, 1, 30, nanosecond=0).

Does that means that I have to manually parse every string I get to get the relevant integers ? Is there a better way to do this ? Like the way the function strptime works (using strings like %Y%m%d to determine the layout of the string)


Solution

  • I learned that from a datetime format it is easy to extract hours for example just by calling date.hour (same for year, month, etc).

    Knowing this, the way to convert a string to a DatetimeWithNanoseconds format takes these 2 easy steps:

    1. Convert the string to a datetime format:
    date = '19551231'
    date = datetime.datetime.strptime(date, '%Y%m%d')
    
    1. Convert to DatetimeWithNanoseconds:
    nano = DatetimeWithNanoseconds(date.year, date.month, date.day, date.hour, date.minute, date.second, nanosecond=0)