python中,怎么把字符串转换为日期格式

如题所述

1、新建python文件,testtime.py;

2、编码代码,将字符串转换为日期格式;

import time

str='2019-12-23 22:18:30'

t = time.strptime(str, '%Y-%m-%d %H:%M:%S')

print(t)

print(type(t))

3、窗口右击选择‘在终端中运行Python文件’;

4、查看执行结果,字符串已转为日期格式;

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-10-08
python中要把字符串转换成日期格式需要使用time模块中的strptime函数,例子如下:
import time
t = time.strptime('2016-05-09 21:09:30', '%Y-%m-%d %H:%M:%S')
print(t)执行结果如下:
time.struct_time(tm_year=2016, tm_mon=5, tm_mday=9, tm_hour=21, tm_min=9, tm_sec=30, tm_wday=0, tm_yday=130, tm_isdst=-1)
函数说明:
第一个参数是要转换成日期格式的字符串,第二个参数是字符串的格式
函数官方文档如下:
Help on built-in function strptime in module time:

strptime(...)
strptime(string, format) -> struct_time

Parse a string to a time tuple according to a format specification.
See the library reference manual for formatting codes (same as
strftime()).

Commonly used format codes:

%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale's equivalent of either AM or PM.

Other codes may be available on your platform. See documentation for the C library strftime function.本回答被提问者采纳
第2个回答  2017-10-07
木兰花(池塘水绿风微暖)