Sven van den Boogaart
Sven van den Boogaart

Reputation: 12323

Python convert string to timestamp

In python im trying to generate a timestamp based on a string input: The data

19/21/2016  12:29:07

First I tried:

import time
import datetime
s = "19/04/2016"
seconds = time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
print seconds

Which worked, than I tried (with same imports):

s = "19/04/2016 12:29:07"
seconds = time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y %H:M:S").timetuple())
print seconds

But I get the following error:

ValueError: time data '19/04/2016 12:29:07' does not match format '%d/%m/%Y %H:M:S'

%H Hour (24-hour clock) as a zero-padded decimal number. %M Minute as a zero-padded decimal number. %S Second as a zero-padded decimal number.

Why is the input not valid when adding the %H:%M:%S ?

Upvotes: 1

Views: 7178

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78546

The problem is not the 24 hour clock. The format of the first string is different from the second in that the second has an impossible value for month - 21.

Update:

Each placeholder should have a preceeding %:

s = "19/04/2016 12:29:07"
format = "%d/%m/%Y  %H:%M:%S"

Upvotes: 2

Related Questions