David542
David542

Reputation: 110093

Format a timestring in python

I have the following datetime as a string:

datestr = "2013-02-20 17:57:25+00:00"

How would I format this in Python as Feb 20, 2013 5:57p.m. ?

Upvotes: 0

Views: 1142

Answers (1)

pyrospade
pyrospade

Reputation: 8078

Use strptime and strftime

http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

>>> import datetime
>>> strptime = datetime.datetime.strptime
>>> s = "2013-02-20 17:57:25+00:00"
>>> # Using s[:-6] to trim off the timezone
>>> strptime(s[:-6], "%Y-%m-%d %H:%M:%S").strftime("%b %d, %Y %I:%M %p")
'Feb 20, 2013 05:57 PM'

Unfortunately, the %z directive doesn't seem to work with strptime

http://bugs.python.org/issue6641

>>> strptime(s, "%Y-%I-%d %H:%M:%S%z")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\apps\Python27\lib\_strptime.py", line 317, in _strptime
    (bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y-%I-%d %H:%M:%S%z'

Upvotes: 4

Related Questions