0

If I have a datetime object, like -

2012-03-10

How would I convert it into the following string format -

Sat, 10 Mar 2012 00:00:00 EDT
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
David542
  • 104,438
  • 178
  • 489
  • 842

3 Answers3

4
datetime.strptime("2012-03-10", "%Y-%m-%d").strftime("%a, %d %b %Y %H:%M:%S EDT")

Sorry about the primitive way of adding the timezone. See this question for better approaches.

Community
  • 1
  • 1
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
1
>>> from datetime import datetime as dt
>>> a = dt.now().replace(tzinfo = pytz.timezone('US/Eastern'))
>>> a.strftime('%a, %d %b %Y %H:%M:%S %Z')
'Fri, 09 Mar 2012 20:02:51 EST'
icyrock.com
  • 27,952
  • 4
  • 66
  • 85
0

Python 3.7+, using dateutil:

from datetime import datetime
from dateutil import tz

s = '2012-03-10'
dt = datetime.fromisoformat(s).replace(tzinfo=tz.gettz('US/Eastern'))
print(dt.strftime('%a, %d %b %Y %H:%M:%S %Z'))
>>> 'Sat, 10 Mar 2012 00:00:00 EST'

Python 3.9+, using zoneinfo:

from datetime import datetime
from zoneinfo import ZoneInfo

s = '2012-03-10'
dt = datetime.fromisoformat(s).replace(tzinfo=ZoneInfo('US/Eastern'))
FObersteiner
  • 22,500
  • 8
  • 42
  • 72