Zack Shapiro
Zack Shapiro

Reputation: 371

Grabbing & displaying the current time

I'm very new to python and trying to build a simple web app in pieces.

I'm using the datetime library for the first time so please be patient with me.

All I'm trying to do is to get and display the current time and date so that I can cross-reference it with a target time & date later.

I'm getting some colossal errors. Any help is appreciated. Not sure what I'm doing incorrectly here to display the time formatted the way I want.

from datetime import datetime

date_string = "4:21 PM 1.24.2011"
format = "%I.%M %p %m %d, %Y"
my_date = datetime.strptime(date_string, format)

print(my_date.strftime(format))

Upvotes: 0

Views: 197

Answers (3)

inspectorG4dget
inspectorG4dget

Reputation: 113905

The problem is with your format. You need to make the format match date_string. So try this:

format = "%I:%M %p %m.%d.%Y"

That should do the trick

Also, it might be of interest to you to take a look at time.asctime

Upvotes: 0

yurymik
yurymik

Reputation: 2224

You're using wrong format string. Try to replace it with "%I:%M %p %m.%d.%Y".

Here's documentation how to use datetime class properly.

Upvotes: 0

hlindset
hlindset

Reputation: 450

The format of the date_string doesn't match the format you're trying to parse it with. The following format string should allow you to parse the date.

 format = "%I:%M %p %m.%d.%Y"

And afterwards, if you want to print it using the other format

print(my_date.strftime("%I.%M %p %m %d, %Y"))

Upvotes: 3

Related Questions