Python程序教程

您现在的位置是:首页 >  Python

当前栏目

Python字符串与时间相互转换

Python,字符串,时间,相互,转换
2025-03-25 08:59:31 时间

大家好,又见面了,我是你们的朋友全栈君。

1、字符串转日期/时间

注意,字符串格式要与参数中时间格式要严格匹配,否则异常

举例:

① 2019-05-01 12:00:00 对应 %Y-%m-%d %H:%M:%S

② 2019-05-01 对应 %Y-%m-%d

2、日期/时间转字符串

3、打印系统当前时间

代码如下:

# coding:utf-8
import datetime
import time

# 1.字符串转日期
detester = '2019-05-01'
date = datetime.datetime.strptime(detester, '%Y-%m-%d')
print(date)

# 2.日期转字符串
date = datetime.datetime.now()
print(date)
detester = date.strftime('%Y-%m-%d')
print(detester)

# 3.打印当前时间
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(current_time)
detester = date.strftime('%Y-%m-%d %H:%M:%S')
print(detester)

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/143855.html原文链接:https://javaforall.cn