Python 时间、字符串转换

String 转 DateTime

1
2
3
In [16]: time_str = '2018-02-28 14:00:00'
In [18]: datetime.datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
Out[18]: datetime.datetime(2018, 2, 28, 14, 0)

DateTime 转 String

1
2
3
In [19]: date_time = datetime.datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
In [20]: date_time.strftime("%Y-%m-%d %H:%M:%S")
Out[20]: '2018-02-28 14:00:00'

DateTime 转 时间戳

1
2
3
4
5
In [21]: date_time
Out[21]: datetime.datetime(2018, 2, 28, 14, 0)

In [22]: time.mktime(date_time.timetuple())
Out[22]: 1519797600.0

时间戳转String

1
2
3
4
5
6
In [22]: time.mktime(date_time.timetuple())
Out[22]: 1519797600.0

In [23]: time_time = time.mktime(date_time.timetuple())
In [24]: time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time_time))
Out[24]: '2018-02-28 14:00:00'

Date转DateTime

1
2
3
4
5
6
7
In [25]: date = datetime.date.today()

In [26]: date
Out[26]: datetime.date(2018, 2, 28)

In [29]: datetime.datetime.strptime(str(date),"%Y-%m-%d")
Out[29]: datetime.datetime(2018, 2, 28, 0, 0)

指定日期

1
2
In [30]: datetime.datetime(2018,2,28)
Out[30]: datetime.datetime(2018, 2, 28, 0, 0)

获取几天前

1
2
3
4
5
6
7
8
9
In [43]: a = datetime.datetime.combine(datetime.date.today(),datetime.time.min)

In [44]: a
Out[44]: datetime.datetime(2018, 2, 28, 0, 0)

In [45]: b = a + datetime.timedelta(-7)

In [46]: b
Out[46]: datetime.datetime(2018, 2, 21, 0, 0)

日期中不要前面的0

1
2
3
4
5
# 例如:01、02、03只要1、2、3
a = datetime.datetime(2018, 2, 28, 0, 0)
time = a.timetuple()
month = time.tm_mon
day = time.tm_mday