I need to convert UTC time, (on ec2 instance) to PST. I am trying to do this.
from datetime import datetime from pytz import timezone import pytz date_format='%m/%d/%Y %H:%M:%S %Z' date = datetime.now() print 'Current date & time is:', date.strftime(date_format) my_timezone=timezone('US/Pacific') date = my_timezone.localize(date) date = date.astimezone(my_timezone) print 'Local date & time is :', date.strftime(date_format)
But the output is:
Current date & time is: 01/10/2012 20:01:14 Local date & time is : 01/10/2012 20:01:14 PST
Any reason why I am not getting the right PST time?
Get the current time using the datetime. now() function(returns the current local date and time) and pass the timezone() function(gets the time zone of a specific location) with the timezone as an argument to it say 'UTC'. Format the above DateTime using the strftime() and print it.
Getting the UTC timestampdatetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC. Lastly, use the timestamp() to convert the datetime object, in UTC, to get the UTC timestamp.
from datetime import datetime from pytz import timezone import pytz date_format='%m/%d/%Y %H:%M:%S %Z' date = datetime.now(tz=pytz.utc) print 'Current date & time is:', date.strftime(date_format) date = date.astimezone(timezone('US/Pacific')) print 'Local date & time is :', date.strftime(date_format)
seems to work for me :) - timezones are confusing, slowly making a plan of what I actually want to do helps me most of the time
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With