简体   繁体   中英

Python how to convert TimeSpan string to DateTime Day

42.00:00:00

This is a TimeSpan value from PowerShell.

How should I go about converting the above string into Python DateTime? I actually only need the day value in a string. The following code does not work with this:

strptime("42.00:00:00", "%d.%H:%M:%S")

I'm assuming it's because of the day being out of day of the month range.

If you only need the day value, you can just split the string on the period, and take the first element.

timespan = "42.00:00:00"
num_days = int(timespan.split(".", 1)[0])

The issue in the conversion you're trying to do is that the PowerShell Timespan is a period of time, and isn't equivalent to a DateTime object though which represents a specific date and time. Instead, you want to convert it to a timedelta object , which also represents a span of time.

So from this code, you can create that object with the following:

from datetime import timedelta
timedelta(days=num_days)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM