473,387 Members | 1,541 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Timezone and ISO8601 struggles with datetime and xml.utils.iso8601.parse

Hello,

I am trying to convert a local time into UTC ISO8601, then parse it
back into local time. I tried the following:

----------------------
#!/usr/bin/python
import time
import datetime
import xml.utils.iso8601

year = 2005
month = 7
day = 22
hour = 10 # This is localtime
minute = 30

mydatetime = datetime.datetime(year, month, day, hour, minute)
strtime = mydatetime.isoformat()

print "Time: " + strtime # Localtime too
mytimestamp = xml.utils.iso8601.parse(strtime)
----------------------

How can I convert this into UTC? Commonsense would have me guess that
the date is converted into UTC on construction of the datetime object,
hovever, this doesn't seem to be the case. I also found the
astimezone(tz) method, but where can I obtain the concrete tz object?

The second problem has to do with the ISO8601 parser, which raises the
following error:

----------------------
Traceback (most recent call last):
File "./timetest.py", line 16, in ?
mytimestamp = xml.utils.iso8601.parse(strtime)
File "/usr/lib/python2.4/site-packages/_xmlplus/utils/iso8601.py",
line 22, in parse
raise ValueError, "unknown or illegal ISO-8601 date format: " + `s`
ValueError: unknown or illegal ISO-8601 date format:
'2005-07-22T10:30:00'
----------------------

Why does it fail to parse the value returned by the datetime object,
and how can I create a parseable time from the datetime object?

Thanks,
-Samuel

Sep 9 '05 #1
2 3704

Samuel> mydatetime = datetime.datetime(year, month, day, hour, minute)
Samuel> strtime = mydatetime.isoformat()

Take a look at the utcoffset method of datetime objects.

Samuel> The second problem has to do with the ISO8601 parser, which
Samuel> raises the following error:

Samuel> ----------------------
Samuel> Traceback (most recent call last):
Samuel> File "./timetest.py", line 16, in ?
Samuel> mytimestamp = xml.utils.iso8601.parse(strtime)
Samuel> File "/usr/lib/python2.4/site-packages/_xmlplus/utils/iso8601.py",
Samuel> line 22, in parse
Samuel> raise ValueError, "unknown or illegal ISO-8601 date format: " + `s`
Samuel> ValueError: unknown or illegal ISO-8601 date format:
Samuel> '2005-07-22T10:30:00'
Samuel> ----------------------

Samuel> Why does it fail to parse the value returned by the datetime
Samuel> object, and how can I create a parseable time from the datetime
Samuel> object?

One possibility might be that datetime objects stringify with microseconds
included:
t = datetime.datetime.now()
t datetime.datetime(2005, 9, 9, 12, 52, 38, 677120) strtime = t.isoformat()
strtime '2005-09-09T12:52:38.677120'

You can try stripping the microseconds first:
time.strptime(strtime, "%Y-%m-%dT%H:%M:%S") Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/Users/skip/local/lib/python2.5/_strptime.py", line 295, in strptime
raise ValueError("unconverted data remains: %s" %
ValueError: unconverted data remains: .677120 time.strptime(strtime.split(".")[0], "%Y-%m-%dT%H:%M:%S")

(2005, 9, 9, 12, 52, 38, 4, 252, -1)

Skip
Sep 9 '05 #2
> Take a look at the utcoffset method of datetime objects.

This returns 0.
However, meanwhile I figured out a way to do this:

Every datetime object by default does not handle timezones at all, and
as such "isoformat" does not return an offset in the ISO8601 string.
The only way around this appears to be passing the tzinfo to the
constructor every time (datetime.tzinfo is not writeable). I am not
aware of a python-provided implementation for a conrete tzinfo, so I
copied this code:

------------------------------------
from datetime import *
import time as _time

STDOFFSET = timedelta(seconds = -_time.timezone)
if _time.daylight:
DSTOFFSET = timedelta(seconds = -_time.altzone)
else:
DSTOFFSET = STDOFFSET

DSTDIFF = DSTOFFSET - STDOFFSET

class LocalTimezone(tzinfo):
def utcoffset(self, dt):
if self._isdst(dt):
return DSTOFFSET
else:
return STDOFFSET

def dst(self, dt):
if self._isdst(dt):
return DSTDIFF
else:
return ZERO

def tzname(self, dt):
return _time.tzname[self._isdst(dt)]

def _isdst(self, dt):
tt = (dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
dt.weekday(), 0, -1)
stamp = _time.mktime(tt)
tt = _time.localtime(stamp)
return tt.tm_isdst > 0
------------------------------------

from the Python documentation into my program. (I am sure there must be
a better way to do this though.) Then, when passing the
tz.LocalTimezone instance to datetime, isoformat() returns the string
with an offset appended (e.g. +02:00).
The resulting string can then also successfully be parsed with
xml.utils.iso8601.parse().

Thanks for your help!

-Samuel

Sep 9 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Paul Bowman | last post by:
HI All I have a date 20020101T000000, 00+00 which is, apparently in the ISO8601 format. I need to get this date into a DateTime instance. This format is different to the style given in the MS...
7
by: Jim Davis | last post by:
I'm (still) working on an ISO 8601 date parser. I want to convert at least the formats described here: http://www.w3.org/TR/NOTE-datetime Well.. I've got most of it working (via RegEx's) good...
3
by: Kevin Kenny | last post by:
Dear All, I have a date time validation method thus: public static bool IsDate(string date, System.IFormatProvider provider) { try { DateTime.Parse(date, provider) return true; } catch...
6
by: Bijoy Naick | last post by:
I have an events table which stores the time of each event - the time and assoicated timezone. Is there a way of converting this time into GMT (with support for DST).. some sort of function which...
3
by: asanford | last post by:
I want to create a web service that allows the caller to pass a DateTime to the web service (that is, create a web method such as void MyWebMethod(DateTime dt).) However, I want to be able to...
0
by: rlaemmler | last post by:
Hi, I just migrated my web app to .NET 2.0. Part of the app creates some business objects from a MySQL query which is returned by a web service. Some of those objects contain DateTime...
11
by: Rubic | last post by:
I was a little surprised to recently discover that datetime has no method to input a string value. PEP 321 appears does not convey much information, but a timbot post from a couple years ago...
5
by: Bill | last post by:
(I forgot to mention that I'm using C#) ------------------- When communicating with a server via webservices, I need to view and set the timezone information for a simple object (it contains one...
4
by: Michael Meckelein | last post by:
Hello, Wondering, if C# (framework 2.0) does not support parsing DateTime timezones in three letter acronyms. I would like to parse date strings like "2005 Nov 01 11:58:47.490 CST -6:00" but...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.