Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Setting a datetime in a specific timezone (without UTC conversions)

Just to be clear, this is python 2.6, I am using pytz.

This is for an application that only deals with US timezones, I need to be able to anchor a date (today), and get a unix timestamp (epoch time) for 8pm and 11pm in PST only.

This is driving me crazy.

> pacific = pytz.timezone("US/Pacific")  > datetime(2011,2,11,20,0,0,0,pacific)  datetime.datetime(2011, 2, 11, 20, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:0 STD>)  > datetime(2011,2,11,20,0,0,0,pacific).strftime("%s") '1297454400'  zsh> date -d '@1297454400'     Fri Feb 11 12:00:00 PST 2011 

So, even though I am setting up a timezone, and creating the datetime with that time zone, it is still creating it as UTC and then converting it. This is more of a problem since UTC will be a day ahead when I am trying to do the calculations.

Is there an easy (or at least sensical) way to generate a timestamp for 8pm PST today?

(to be clear, I do understand the value of using UTC in most situations, like database timestamps, or for general storage. This is not one of those situations, I specifically need a timestamp for evening in PST, and UTC should not have to enter into it.)

like image 217
liam Avatar asked Feb 11 '11 22:02

liam


People also ask

How do you get the time in a specific timezone Python?

To get the current time of a timezone, you need to create a timezone object by using the pytz. timezone() method and pass it to the datetime. now() method. Then, it'll return the current time of that specific timezone.

How do you convert UTC time to local time in Python?

This datetime object will have no timezone associated with it. Therefore assign the UTC timezone to this datetime object using replace(tzinfo=pytz. UTC) function. Convert the timezone of the datetime object to local timezone by calling the astimezone() function on datetime object.


1 Answers

There are at least two issues:

  1. you shouldn't pass a timezone with non-fixed UTC offset such as "US/Pacific" as tzinfo parameter directly. You should use pytz.timezone("US/Pacific").localize() method instead
  2. .strftime('%s') is not portable, it ignores tzinfo, and it always uses the local timezone. Use datetime.timestamp() or its analogs on older Python versions instead.

To make a timezone-aware datetime in the given timezone:

#!/usr/bin/env python from datetime import datetime  import pytz # $ pip install pytz  tz = pytz.timezone("US/Pacific") aware = tz.localize(datetime(2011, 2, 11, 20), is_dst=None) 

To get POSIX timestamp:

timestamp = (aware - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds() 

(On Python 2.6, see totimestamp() function on how to emulate .total_seconds() method).

like image 88
jfs Avatar answered Sep 20 '22 04:09

jfs