当前位置:网站首页>[1154]如何将字符串转换为datetime
[1154]如何将字符串转换为datetime
2022-07-31 01:47:00 【周小董】
#!/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
参考:https://www.php.cn/python-tutorials-420250.html
边栏推荐
猜你喜欢
仿牛客网项目总结
最大路径和
想要写出好的测试用例,先要学会测试设计
Jiuzhou Cloud was selected into the "Trusted Cloud's Latest Evaluation System and the List of Enterprises Passing the Evaluation in 2022"
Crypto Life, a day in the life of a Web3 project partner
手把手教你配置Jenkins自动化邮件通知
"Cloud native's master, master and vulgar skills" - 2022 National New College Entrance Examination Volume I Composition
MySql installation and configuration super detailed tutorial and simple method of building database and table
MySQL (6)
Xiaohei's leetcode journey: 104. The maximum depth of a binary tree
随机推荐
android的webview缓存相关知识收集
《MySQL数据库进阶实战》读后感(SQL 小虚竹)
太阳能板最大面积 od js
MySQL (6)
What have I experienced when I won the offer of BAT and TMD technical experts?
汉诺塔问题
成为比开发硬气的测试人,我都经历了什么?
Charging effect simulation
.NET 跨平台应用开发动手教程 |用 Uno Platform 构建一个 Kanban-style Todo App
1782. Count the number of point pairs Double pointer
PDF split/merge
Multiplication, DFS order
MySQL (6)
Distributed. Idempotency
1.非类型模板参数 2.模板的特化 3.继承讲解
初识C语言 -- 数组
My first understanding of MySql, and the basic syntax of DDL and DML and DQL in sql statements
倍增、DFS序
《云原生的本手、妙手和俗手》——2022全国新高考I卷作文
第一学年课程期末考试