Python 时间转换

2018-07-20  本文已影响0人  octocat
# 不加时区转换
>> import datetime
>> datetime.datetime.strptime('1991-12-17', '%Y-%m-%d')
datetime.datetime(1991, 12, 17, 0, 0)
# 加时区
>> import pytz
>> datetime.datetime.strptime('1991-12-17', '%Y-%m-%d').replace(tzinfo = pytz.timezone('Asia/Shanghai'))
datetime.datetime(1991, 12, 17, 0, 0, tzinfo=<DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>)
# 在Django中转化加时区(原理和上面一样)
>> from django.utils import timezone
# 默认时区是timezone.get_current_timezone()。从settings里面获取的
>> timezone.make_aware(datetime.datetime.strptime('1991-12-17', '%Y%m%d'))
datetime.datetime(1991, 12, 17, 0, 0, tzinfo=<DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>)
# 使用dateutil
# 可以转化的字符串比较自由
>> from dateutil.parser import parse
>> parse("Wed, Nov 12")
datetime.datetime(2018, 11, 12, 0, 0)
>> import datetime
>> my_time = datetime.datetime.strptime('1991-12-17', '%Y-%m-%d')
>> my_time.strftime(format = '%Y-%m-%d')
1991-12-17
>> import datetime
>> datetime.timedelta(seconds = 1)
datetime.timedelta(0, 1)
# 使用relativedelta可以获得比timedelta更长的时间单位,比如年
>> from dateutil.relativedelta import relativedelta
>> relativedelta(seconds = 1)
relativedelta(seconds=+1)
>> relativedelta(years = 1)
relativedelta(years=+1)
上一篇下一篇

猜你喜欢

热点阅读