python时间与Unix时间戳相互转换方法详解

作者:猪笨是念来过倒 时间:2023-07-11 02:09:12 

对于时间数据,如2018-09-25 09:28:59,有时需要与Unix时间戳进行相互的运算,此时就需要对两种形式进行转换,在Python中,转换时需要用到time模块,具体的函数如下:

其中unix_time函数是正常时间转unix时间,local_time是unix时间转正常时间。


import time

def unix_time(dt):
 #转换成时间数组
 timeArray = time.strptime(dt, "%Y-%m-%d %H:%M:%S")
 #转换成时间戳
 timestamp = time.mktime(timeArray)
 return timestamp

def local_time(timestamp):
 #转换成localtime
 time_local = time.localtime(timestamp)
 #转换成新的时间格式(2016-05-05 20:28:54)
 dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
 return dt

if __name__ == '__main__':
 time_now = '2018-09-25 15:33:20'
 unix_t = unix_time(time_now)
 local_t = local_time(unix_t)
 print(unix_t)

来源:https://blog.csdn.net/liao392781/article/details/82835892

标签:python,时间戳
0
投稿

猜你喜欢

  • ASP实现文件直接下载的代码

    2011-04-11 10:56:00
  • Python操作PDF文件之实现A3页面转A4

    2021-03-06 19:45:06
  • Python实现实时显示进度条的六种方法

    2022-03-27 02:09:35
  • Python解压 rar、zip、tar文件的方法

    2023-07-22 10:51:38
  • 互联网产品的用户体验看着“很美”

    2009-07-07 12:04:00
  • asp如何在数据库中用好Transaction?

    2010-06-22 21:07:00
  • python图形用户接口实例详解

    2023-10-17 21:05:20
  • 王孟友教你如何设计标志(LOGO)

    2008-04-17 13:30:00
  • 详解python中的Turtle函数库

    2021-10-17 19:50:45
  • 跟老齐学Python之集合的关系

    2023-02-04 22:32:27
  • Go语言流程控制详情

    2023-10-16 13:16:24
  • innerHTML 引发“未知的运行时错误”

    2008-04-09 13:06:00
  • Hibernate Oracle sequence的使用技巧

    2023-07-06 05:18:42
  • python爬取一组小姐姐图片实例

    2023-08-03 15:05:45
  • python实现简单倒计时功能

    2022-09-29 03:08:32
  • Python常见数据结构详解

    2021-10-28 22:07:33
  • django 基于中间件实现限制ip频繁访问过程详解

    2022-06-24 08:38:43
  • python 切片和range()用法说明

    2021-12-12 07:40:52
  • 在PHP程序中运行Python脚本(接收数据及传参)的方法详解

    2023-11-24 10:14:48
  • python re正则表达式模块(Regular Expression)

    2021-01-26 20:22:26
  • asp之家 网络编程 m.aspxhome.com