2025年2月24日 星期一 甲辰(龙)年 腊月廿四 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

如何将字符串转换为datetime

时间:09-01来源:作者:点击数:29

如何将字符串转换为datetime

  • #!/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

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐