Python unix timestamp conversion and timezone
Hey all! Ive got timezone troubles.
I have a time stamp of 2010-07-26 23:35:03
What I really want to do is subtract 15 minutes from that time.
My method was going to be a simple conversion to unix time, subtract the seconds and convert back. Simple right?
My problem is that python adjusts the returned unix time using my local timezone, currently eastern daylight savings time which I believe is GMT -4.
开发者_如何转开发So when I do this:
# packet[20] holds the time stamp
unix_time_value = (mktime(packet[20].timetuple()))
I get 1280201703 which is Tue, 27 Jul 2010 03:35:03. I can do this:
unix_time_value = (mktime(packet[20].timetuple())) - (4 * 3600)
but now I have to check for eastern standard time which is -5 GMT and adjust the (4 * 3600) to (5 * 3600). Is there any way to tell python to not use my local timezone and just convert the darn timestamp OR is there an easy way to take packet[20] and subtract 15 minutes?
Subtract datetime.timedelta(seconds=15*60)
.
The online docs have a handy table (what you call "unix time" is more properly called "UTC", for "Universal Time Coordinate", and "seconds since the epoch" is a "timestamp" as a float...):
Use the following functions to convert between time representations:
From To Use
seconds since the epoch struct_time in UTC gmtime()
seconds since the epoch struct_time in local time localtime()
struct_time in UTC seconds since the epoch calendar.timegm()
struct_time in local time seconds since the epoch mktime()
where the unqualified function names come from the time
module (since that's where the docs are;-). So, since you apparently start with a struct_time in UTC
, use calendar.timegm()
to get the timestamp (AKA "seconds since the epoch"), subtract 15 * 60 = 900
(since the units of measure are seconds), and put the resulting "seconds since the epoch" back into a struct_time in UTC
with time.gmtime
. Or, use time.mktime
and time.localtime
if you prefer to work in local times (but that might give problem if the 15 minutes can straddle the instant in which it switches to DST or back -- always working in UTC is much sounder).
Of course, to use calendar.timegm
, you'll need an import calendar
in your code (imports are usually best placed at the top of the script or module).
Scroll down and read about subtracting from a date: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
精彩评论