473,242 Members | 1,488 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,242 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 3692

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: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.