Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set timezone to eastern for DateTime module in python? [duplicate]

I'm utilizing the datetime module to produce the current date. However, when I run this after 7PM, the current date becomes tomorrow's date.

I'm not sure how to set the time zone for the following module

from datetime import *
print date.today()

I've read the documentation but have not found how to set this yet.

like image 730
Chris Avatar asked Dec 05 '22 01:12

Chris


1 Answers

Your date is a "naive" datetime, it doesn't have a timezone (tz=None). Then you have to localize this datetime by setting a timezone. Use pytz module to do that.

Here is an example :

from datetime import datetime
from pytz import timezone
# define date format
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
# define eastern timezone
eastern = timezone('US/Eastern')
# naive datetime
naive_dt = datetime.now()
# localized datetime
loc_dt = datetime.now(eastern)
print(naive_dt.strftime(fmt))
# 2015-12-31 19:21:00 
print(loc_dt.strftime(fmt))
# 2015-12-31 19:21:00 EST-0500

Read pytz documentation for more information

like image 151
Louis Barranqueiro Avatar answered Dec 06 '22 15:12

Louis Barranqueiro