timedelta problem
Denis McMahon
denismfmcmahon at gmail.com
Fri Aug 15 05:36:39 EDT 2014
On Fri, 15 Aug 2014 10:24:47 +0800, luofeiyu wrote:
> problem :
>
> t1 is GMT time 2014 00:36:46 t2 is GMT time 2014 14:36:46
>
> datetime.datetime.strptime do not give me the right answer.
As far as I can tell from running the following, it all seems to work as
expected in python 3.2 (and hence I expect in 3.4). If the expected
output doesn't match yours, it would be interesting to see what your
output is. If the expected output does match yours, and you think it's
wrong, it would be interesting to know which bits you think are wrong and
why you think they are wrong, because having a fair bit of the night
looking at this, it all looks good to me.
#!/usr/bin/python3
from datetime import tzinfo, timedelta, datetime, timezone
# define timedelta based timezones
UTCm7 = timezone(timedelta(0,-7*3600),"UTC-07:00")
UTCp7 = timezone(timedelta(0,+7*3600),"UTC+07:00")
UTC = timezone(timedelta(0), "UTC+00:00")
# some timestrings
t1 = 'Sat, 09 Aug 2014 07:36:46 -0700'
t2 = 'Sat, 09 Aug 2014 07:36:46 +0700'
t3 = 'Sat, 09 Aug 2014 07:36:46 +0000'
# make some datetime objects
# these are both utc -7
a1 = datetime.strptime(t1,"%a, %d %b %Y %H:%M:%S %z")
b1 = datetime(2014, 8, 9, 7, 36, 46, tzinfo = UTCm7)
# these are both utc +7
a2 = datetime.strptime(t2,"%a, %d %b %Y %H:%M:%S %z")
b2 = datetime(2014, 8, 9, 7, 36, 46, tzinfo = UTCp7)
# these are both utc
a3 = datetime.strptime(t3,"%a, %d %b %Y %H:%M:%S %z")
b3 = datetime(2014, 8, 9, 7, 36, 46, tzinfo = UTC)
# print them out as stored
print( "UTC -7:" )
print( t1 )
print( a1 )
print( b1 )
print( "UTC +7:" )
print( t2 )
print( a2 )
print( b2 )
print( "UTC:" )
print( t3 )
print( a3 )
print( b3 )
# print them out converted to UTC
print( "UTC -7 as UTC:" )
print( a1.astimezone( UTC ) )
print( b1.astimezone( UTC ) )
print( "UTC +7 as UTC:" )
print( a2.astimezone( UTC ) )
print( b2.astimezone( UTC ) )
print( "UTC as UTC:" )
print( a3.astimezone( UTC ) )
print( b3.astimezone( UTC ) )
# expected output
"""
UTC -7:
Sat, 09 Aug 2014 07:36:46 -0700
2014-08-09 07:36:46-07:00
2014-08-09 07:36:46-07:00
UTC +7:
Sat, 09 Aug 2014 07:36:46 +0700
2014-08-09 07:36:46+07:00
2014-08-09 07:36:46+07:00
UTC:
Sat, 09 Aug 2014 07:36:46 +0000
2014-08-09 07:36:46+00:00
2014-08-09 07:36:46+00:00
UTC -7 as UTC:
2014-08-09 14:36:46+00:00
2014-08-09 14:36:46+00:00
UTC +7 as UTC:
2014-08-09 00:36:46+00:00
2014-08-09 00:36:46+00:00
UTC as UTC:
2014-08-09 07:36:46+00:00
2014-08-09 07:36:46+00:00
"""
--
Denis McMahon, denismfmcmahon at gmail.com
More information about the Python-list
mailing list