python 时间字符串与日期转化

python 时间字符串与日期转化

datetime.datetime.strptime(string, format)

根据指定的格式解析字符串为一个datetime类型。相当于datetime.datetime(*time.strptime(string, format)[0:6])。

In [1]: import datetime

In [2]: s = '2015-10-28 18:33'

In [3]: datetime.datetime.strptime(s, '%Y-%m-%d %H:%M')
Out[3]: datetime.datetime(2015, 10, 28, 18, 33)

In [4]: import time

In [5]: datetime.datetime(*time.strptime(s, '%Y-%m-%d %H:%M')[0:6])
Out[5]: datetime.datetime(2015, 10, 28, 18, 33)

格式化输出日期

  • datetime.datetime.strftime
    也可以使用time.strftime进行格式化输出。
In [6]: dt = datetime.datetime(*time.strptime(s, '%Y-%m-%d %H:%M')[0:6])

In [9]: dt.strftime('%Y/%m/%d %H:%M')
Out[9]: '2015/10/28 18:33'

  • 字符串格式化
In [10]: '{:%Y%m%d %H:%M}'.format(dt)
Out[10]: '20151028 18:33'

原文地址:https://www.cnblogs.com/xianwang/p/4931664.html