I am trying to change the date format using python datetime.strptime, but a Value Error appears.

Asked 1 years ago, Updated 1 years ago, 81 views

The data I want to format is date data in the format [20160610]T[0].

Bring to repeat statement

Use datetime.strptime to make that data into a single string like '%sT%s'

The format is "[%Y%m%d]T[%H%M%S]".

ValueError: does not match format appears.

The cause seems to be an error because the data is only [0] in the middle of getting the format [%H%M%S].

4-5 digit data that is less than 6 digits, such as other data [12531] and [12239] is

A zero is inserted automatically in minutes or seconds

It was automatically mapped to 1:2531 or 1:22:39, so there was no problem with the conversion.

The problem only occurs when the low digit is 1 or 2 digits.

I'd appreciate your help.

python date format datetime strptime

2022-09-22 21:12

1 Answers

If you want to read it in three different ways: time/minute/second, but the input length is less than 3, there is no way to match it in time/minute/second.

import datetime
datetime.datetime.strptime("12","%M%S")

as above, error does not result in even two party leaders, s m percent.

If the length is less than 3, why don't you fill it in with 0 as shown below?

text = '[20160714]T[21]'

digits = len(text[12:-1])
if digits < 3:
    text = text[:-1]+("0"*(3-digits))+"]"

print(text)


2022-09-22 21:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.