Python 时间转换

  • 字符串转datetime
# 不加时区转换
>> 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=)
# 在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=)
# 使用dateutil
# 可以转化的字符串比较自由
>> from dateutil.parser import parse
>> parse("Wed, Nov 12")
datetime.datetime(2018, 11, 12, 0, 0)
  • datetime 转字符串
>> 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)

你可能感兴趣的:(Python 时间转换)