time模組 日期轉換

2021-09-20 01:31:23 字數 2244 閱讀 8167

一種獲取當前時間,以及時間格式化的模組

time模組在python原生安裝中就存在,直接使用即可,無需額外的安裝操作

# -*- coding: utf-8 -*-

import time

import locale

設定本地語言型別為中文

locale.setlocale(locale.lc_ctype,"chinese")

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

time模組-常用方法

time模組-時間元組

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)

python 日期模組 (time模組)

在python中與事件處理相關的模組有 time datetime calendar 這裡先講解time模組 1.time 模組的引入用import time 1 time.time 返回當前時間的時間戳 1970紀元後經過的浮點秒數 返回結果資料型別是float import time temp ...

Python日期格式化 time模組

time.struct time tm year 2019 tm mon 5,tm mday 17,tm hour 14,tm min 26,tm sec 53,tm wday 4,tm yday 137,tm isdst 0 time.struct time tm year 2019 tm mon...

python中time模組轉換Unix時間戳

dota2資料中遊戲開始時間儲存為unix時間戳,為了展示需要轉換成北京時間。使用localtime 進行計算。1,使用gmtime將unix時間戳轉換為格林尼治時間 2,使用localtime將unix時間戳轉換為當地時間 from touse seconds since the epoch st...