python time type conversion

 

    We use the python datetime module context when comparing two time, there will be an error:

  TypeError: can't compare offset-naive and offset-aware datetimes

  This is because the two time is not of the same type, offset-naive type is no time zone, the offset-aware type region is sometimes, both naturally can not compare.

  We can determine the object tzinfo datetime attribute to learn that he is what type

In [17]: import datetime
 
In [18]: import pytz
 
In [19]: now=datetime.datetime.now()
 
In [20]: now
Out[20]: datetime.datetime(2016, 11, 13, 16, 23, 37, 488000)
 
In [21]: now.tzinfo==None
Out[21]: True

  The above code is now a offset-naive type is datetime a free time zone. The following code can convert it to a time offset-aware type zone comprising:

In [22]: now=now.replace(tzinfo=pytz.timezone('UTC'))
 
In [23]: now
Out[23]: datetime.datetime(2016, 11, 13, 16, 23, 37, 488000, tzinfo=<UTC>)
 
In [24]: now.tzinfo
Out[24]: <UTC>

  Similarly, an offset-aware converter to offset-naive type:

In [25]: now=now.replace(tzinfo=None)
 
In [26]: now
Out[26]: datetime.datetime(2016, 11, 13, 16, 23, 37, 488000)

    We use the python datetime module context when comparing two time, there will be an error:

  TypeError: can't compare offset-naive and offset-aware datetimes

  This is because the two time is not of the same type, offset-naive type is no time zone, the offset-aware type region is sometimes, both naturally can not compare.

  We can determine the object tzinfo datetime attribute to learn that he is what type

In [17]: import datetime
 
In [18]: import pytz
 
In [19]: now=datetime.datetime.now()
 
In [20]: now
Out[20]: datetime.datetime(2016, 11, 13, 16, 23, 37, 488000)
 
In [21]: now.tzinfo==None
Out[21]: True

  The above code is now a offset-naive type is datetime a free time zone. The following code can convert it to a time offset-aware type zone comprising:

In [22]: now=now.replace(tzinfo=pytz.timezone('UTC'))
 
In [23]: now
Out[23]: datetime.datetime(2016, 11, 13, 16, 23, 37, 488000, tzinfo=<UTC>)
 
In [24]: now.tzinfo
Out[24]: <UTC>

  Similarly, an offset-aware converter to offset-naive type:

In [25]: now=now.replace(tzinfo=None)
 
In [26]: now
Out[26]: datetime.datetime(2016, 11, 13, 16, 23, 37, 488000)

Guess you like

Origin www.cnblogs.com/xiaomage666/p/11386979.html
Recommended