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
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
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.
>>> 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'
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'))