Python获取当前时间

1. 先导入库:import datetime

2.获取当前日期和时间:now_time = datetime.datetime.now()

3.格式化成我们想要的日期:strftime()

   比如:“2018-10-25 10:00:20”:datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

(1)字符串转datetime:
>>> string = '2014-01-08 11:59:58'
>>> time1 = datetime.datetime.strptime(string,'%Y-%m-%d %H:%M:%S')
>>> print time1
2014-01-08 11:59:58

(2)datetime转字符串:
>>> time1_str = datetime.datetime.strftime(time1,'%Y-%m-%d %H:%M:%S')
>>> time1_str
'2014-01-08 11:59:58'

(3)时间戳转时间对象:

>>>time1 = time.localtime()

>>>time1_str = datetime.datetime.fromtimestamp(time1)

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