time模块 - 日期转换

简介: ==== 模块名称:time ====一种获取当前时间,以及时间格式化的模块time模块在Python原生安装中就存在,直接使用即可,无需额外的安装操作== 导入方式:import time ==# -*- coding: utf-8 -*-import timeimport locale设置本地语言类型为中文locale.

==== 模块名称:time ====

一种获取当前时间,以及时间格式化的模块
time模块在Python原生安装中就存在,直接使用即可,无需额外的安装操作

== 导入方式:import time ==

# -*- coding: utf-8 -*-
import time
import locale
设置本地语言类型为中文
locale.setlocale(locale.LC_CTYPE,"chinese")

=== 获取当前时间 时间戳 从1970:01:01 00:00:00 ===

now_time = time.time()
print("时间戳:", now_time)

时间戳: 1536543970.762821

=== 将时间戳转为日期格式的元组 ===

now_tuple = time.localtime(now_time)
print("日期格式元组:", now_tuple)

日期格式元组: time.struct_time(tm_year=2018, tm_mon=9, tm_mday=10, tm_hour=9, tm_min=46, tm_sec=10, tm_wday=0, tm_yday=253, tm_isdst=0)

=== 元组转时间格式 ===

注意:开头locale.setlocale不加,strftime会解析失败)

print(time.strftime("%Y-%m-%d %H:%M:%S",now_tuple))

2018-09-10 16:59:19

=== 可读类型日期转元组和时间戳 ===

把可读类型的日期格式转化成时间元祖
date_tuple = time.strptime("2018-09-10 17:20:24",'%Y-%m-%d %H:%M:%S')`
把可读类型的日期格式转化成时间元祖
now_timestamp = time.mktime(date_tuple)
print("元组:",date_tuple)
print("时间戳:",now_timestamp)

元组: time.struct_time(tm_year=2018, tm_mon=9, tm_mday=10, tm_hour=17, tm_min=20, tm_sec=24, tm_wday=0, tm_yday=253, tm_isdst=-1)
时间戳: 1536571224.0

img_fe354041575502b9fde1844b81dedca4.png
time模块-常用方法
img_941110791b82f76b10d16a9acccffeec.png
time模块-时间元组
img_79eb046445616c736c701b9b45886947.png
time模块-时间格式

=== 完整的代码 ===

# -*- coding: utf-8 -*-
import time
import locale
#设置本地语言类型为中文
locale.setlocale(locale.LC_CTYPE,"chinese")

#获取当前时间 时间戳 从1970:01:01 00:00:00
now_time = time.time()
print("时间戳:", now_time)

#将时间戳转为 日期格式的元组
now_tuple = time.localtime(now_time)
print("日期格式元组:", now_tuple)

#时间格式(注意:开头locale.setlocale不加,strftime会解析失败)
now_date = time.strftime("%Y-%m-%d %H:%M:%S",now_tuple)
print(now_date)

#把可读类型的日期格式转化成时间元祖
date_tuple = time.strptime("2018-09-10 17:20:24",'%Y-%m-%d %H:%M:%S')
#把可读类型的日期格式转化成时间元祖
now_timestamp = time.mktime(date_tuple)
print("元组:",date_tuple)
print("时间戳:",now_timestamp)
相关文章
|
7月前
|
存储 Linux C语言
Python标准库分享之时间与日期 (time, datetime包)
Python标准库分享之时间与日期 (time, datetime包)
|
6月前
Easyui validatebox增加对time、date、datetime的验证,时间格式化
Easyui validatebox增加对time、date、datetime的验证,时间格式化
|
9月前
|
Java
time类获取时间
time类获取时间
75 0
|
9月前
|
Unix C语言 Python
|
12月前
|
Python
Python 与时间、日期相关的库 time, datetime, calendar
Python 与时间、日期相关的库 time, datetime, calendar
59 0
Golang:time模块获取当前日期/时间戳并格式化输出
Golang:time模块获取当前日期/时间戳并格式化输出
103 0
|
API Android开发
Date & Time组件(上)
本节给大家带来的是Android给我们提供的显示时间的几个控件,他们分别是: TextClock,AnalogClock,Chronometer,另外其实还有个过时的DigitalClock就不讲解了! 好的,开始本节内容!
95 0
PHP:时间戳time和日期格式字符串转换date
PHP:时间戳time和日期格式字符串转换date
|
Python
Python编程:time和datetime时间模块详解
Python编程:time和datetime时间模块详解
157 0
Python编程:time和datetime时间模块详解
|
Unix Python
python 时间模块 time datetime calendar
学而时习之,不亦悦乎。经常的复习下之前的知识,不仅加深、巩固记忆,还能在复习的同时,查漏补缺。 今天针对python库自带的三个时间模块进行复习。。。。
122 0

热门文章

最新文章