本文摘自php中文网,作者anonymity,侵删。
在Python中对于时间和字符串之间的转换很常见,但是具体是怎么实现的,如何将字符串转换为datetime呢?
案例:time & datetime & string 相互转换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import datetime
import time
# 日期时间字符串
st = "2017-11-23 16:10:10"
# 当前日期时间
dt = datetime.datetime.now()
# 当前时间戳
sp = time.time()
# 1.把datetime转成字符串
def datetime_toString(dt):
print ( "1.把datetime转成字符串: " , dt. strftime ( "%Y-%m-%d %H:%M:%S" ))
# 2.把字符串转成datetime
def string_toDatetime(st):
print ( "2.把字符串转成datetime: " , datetime.datetime. strptime (st, "%Y-%m-%d %H:%M:%S" ))
# 3.把字符串转成时间戳形式
def string_toTimestamp(st):
print ( "3.把字符串转成时间戳形式:" , time. mktime (time. strptime (st, "%Y-%m-%d %H:%M:%S" )))
# 4.把时间戳转成字符串形式
def timestamp_toString(sp):
print ( "4.把时间戳转成字符串形式: " , time. strftime ( "%Y-%m-%d %H:%M:%S" , time.localtime(sp)))
# 5.把datetime类型转外时间戳形式
def datetime_toTimestamp(dt):
print ( "5.把datetime类型转外时间戳形式:" , time. mktime (dt.timetuple()))
# 1.把datetime转成字符串
datetime_toString(dt)
# 2.把字符串转成datetime
string_toDatetime(st)
# 3.把字符串转成时间戳形式
string_toTimestamp(st)
# 4.把时间戳转成字符串形式
timestamp_toString(sp)
# 5.把datetime类型转外时间戳形式
datetime_toTimestamp(dt)
|
实验结果:
1.把datetime转成字符串: 2017-11-23 17:05:18
2.把字符串转成datetime: 2017-11-23 16:10:10
3.把字符串转成时间戳形式: 1511424610.0
4.把时间戳转成字符串形式: 2017-11-23 17:05:18
5.把datetime类型转外时间戳形式: 1511427918.0
以上就是如何将字符串转换为datetime的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
用Python语言描述最大连续子序列和
Python爬虫学到什么程度能找到工作
Python tkinter是什么
实例介绍Python文件操作删除某行方法
Python运算符-实战中常用的三个逻辑运算符使用实例
自学Python看什么
一种解释型语言--Python的介绍
对Python中gensim库word2vec的使用
Python pycurl验证basic和digest认证的方法
Python列表如何去重
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » 如何将字符串转换为datetime