时间戳转换工具
时间格式
当前时间信息
当前时间
秒级时间戳
毫秒级时间戳
时间戳转换
时间戳 → 时间
时间戳
转换结果
时间 → 时间戳
时间
秒级
毫秒级
小知识
什么是时间戳?
时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。通俗的讲,时间戳是一份能够表示一份数据在一个特定时间点已经存在的完整的可验证的数据。
秒级 vs 毫秒级
秒级时间戳:从1970年1月1日开始的秒数,通常为10位数字。
毫秒级时间戳:从1970年1月1日开始的毫秒数,通常为13位数字。
示例代码
各语言示例代码
-
获取时间戳 (C)
1#include <stdio.h> 2#include <time.h> 3#include <sys/time.h> 4#include <string.h> 5 6int main() { 7 time_t current_time; 8 struct tm *time_info; 9 char time_string[100]; 10 11 // 获取当前时间戳(秒级) 12 current_time = time(NULL); 13 printf("当前时间戳(秒):%ld\n", current_time); 14 15 // 获取当前时间戳(毫秒级) 16 struct timeval tv; 17 gettimeofday(&tv, NULL); 18 long milliseconds = tv.tv_sec * 1000 + tv.tv_usec / 1000; 19 printf("当前时间戳(毫秒):%ld\n", milliseconds); 20 21 // 获取当前时间戳(微秒级) 22 long microseconds = tv.tv_sec * 1000000 + tv.tv_usec; 23 printf("当前时间戳(微秒):%ld\n", microseconds); 24 25 // 获取指定时间的时间戳 26 struct tm specific_time = {0}; 27 specific_time.tm_year = 2024 - 1900; // 年份需要减去1900 28 specific_time.tm_mon = 0; // 月份从0开始(0=1月) 29 specific_time.tm_mday = 1; 30 specific_time.tm_hour = 12; 31 specific_time.tm_min = 0; 32 specific_time.tm_sec = 0; 33 34 time_t specific_timestamp = mktime(&specific_time); 35 printf("指定时间的时间戳(秒):%ld\n", specific_timestamp); 36 37 // 时间戳转换为时间 38 time_t timestamp = 1704067200; // 2024-01-01 12:00:00 39 time_info = localtime(×tamp); 40 strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", time_info); 41 printf("时间戳转时间:%s\n", time_string); 42 43 // 字符串时间转换为时间戳 44 char time_str[] = "2024-01-01 12:00:00"; 45 struct tm parsed_time = {0}; 46 if (strptime(time_str, "%Y-%m-%d %H:%M:%S", &parsed_time) != NULL) { 47 time_t timestamp_from_str = mktime(&parsed_time); 48 printf("字符串时间转时间戳:%ld\n", timestamp_from_str); 49 } else { 50 printf("解析时间字符串失败\n"); 51 } 52 53 // 格式化当前时间 54 time_info = localtime(¤t_time); 55 strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", time_info); 56 printf("当前时间(标准格式):%s\n", time_string); 57 58 strftime(time_string, sizeof(time_string), "%Y年%m月%d日 %H时%M分%S秒", time_info); 59 printf("当前时间(中文格式):%s\n", time_string); 60 61 // 时间戳字符串转换 62 char timestamp_str[] = "1704067200"; 63 long timestamp_int = atol(timestamp_str); 64 time_info = localtime(×tamp_int); 65 strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", time_info); 66 printf("字符串时间戳转时间:%s\n", time_string); 67 68 // 获取时区信息 69 time_info = localtime(¤t_time); 70 printf("当前时区偏移:%ld秒\n", time_info->tm_gmtoff); 71 72 // 获取UTC时间 73 time_info = gmtime(¤t_time); 74 strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", time_info); 75 printf("UTC时间:%s\n", time_string); 76 77 // 时间计算示例 78 time_t one_hour_later = current_time + 3600; 79 time_info = localtime(&one_hour_later); 80 strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", time_info); 81 printf("一小时后的时间:%s\n", time_string); 82 83 time_t one_day_later = current_time + 86400; 84 time_info = localtime(&one_day_later); 85 strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", time_info); 86 printf("一天后的时间:%s\n", time_string); 87 88 // 时间差计算 89 time_t time1 = 1704067200; // 2024-01-01 12:00:00 90 time_t time2 = 1704153600; // 2024-01-02 12:00:00 91 double time_diff = difftime(time2, time1); 92 printf("时间差(秒):%.0f\n", time_diff); 93 printf("时间差(小时):%.2f\n", time_diff / 3600); 94 printf("时间差(天):%.2f\n", time_diff / 86400); 95 96 // 获取各种时间格式 97 time_info = localtime(¤t_time); 98 99 // ISO格式 100 strftime(time_string, sizeof(time_string), "%Y-%m-%dT%H:%M:%S%z", time_info); 101 printf("ISO格式:%s\n", time_string); 102 103 // RFC格式 104 strftime(time_string, sizeof(time_string), "%a, %d %b %Y %H:%M:%S %z", time_info); 105 printf("RFC格式:%s\n", time_string); 106 107 // 自定义格式 108 strftime(time_string, sizeof(time_string), "%Y/%m/%d %H:%M:%S", time_info); 109 printf("斜杠格式:%s\n", time_string); 110 111 // 获取时间组件 112 printf("年:%d\n", time_info->tm_year + 1900); 113 printf("月:%d\n", time_info->tm_mon + 1); 114 printf("日:%d\n", time_info->tm_mday); 115 printf("时:%d\n", time_info->tm_hour); 116 printf("分:%d\n", time_info->tm_min); 117 printf("秒:%d\n", time_info->tm_sec); 118 printf("星期:%d\n", time_info->tm_wday); 119 printf("一年中的第几天:%d\n", time_info->tm_yday); 120 121 // 使用clock()函数获取CPU时间 122 clock_t cpu_time = clock(); 123 printf("CPU时间(时钟周期):%ld\n", cpu_time); 124 printf("CPU时间(秒):%.2f\n", (double)cpu_time / CLOCKS_PER_SEC); 125 126 return 0; 127}
-
获取时间戳 (GO)
1package main 2 3import ( 4 "fmt" 5 "strconv" 6 "time" 7) 8 9func main() { 10 // 获取当前时间戳(秒级) 11 currentTimestampSeconds := time.Now().Unix() 12 fmt.Printf("当前时间戳(秒):%d\n", currentTimestampSeconds) 13 14 // 获取当前时间戳(毫秒级) 15 currentTimestampMilliseconds := time.Now().UnixMilli() 16 fmt.Printf("当前时间戳(毫秒):%d\n", currentTimestampMilliseconds) 17 18 // 获取当前时间戳(纳秒级) 19 currentTimestampNano := time.Now().UnixNano() 20 fmt.Printf("当前时间戳(纳秒):%d\n", currentTimestampNano) 21 22 // 获取指定时间的时间戳 23 specificTime := time.Date(2024, 1, 1, 12, 0, 0, 0, time.Local) 24 specificTimestamp := specificTime.Unix() 25 fmt.Printf("指定时间的时间戳(秒):%d\n", specificTimestamp) 26 27 // 时间戳转换为时间 28 timestamp := int64(1704067200) // 2024-01-01 12:00:00 29 dateFromTimestamp := time.Unix(timestamp, 0) 30 fmt.Printf("时间戳转时间:%s\n", dateFromTimestamp.Format("2006-01-02 15:04:05")) 31 32 // 字符串时间转换为时间戳 33 timeStr := "2024-01-01 12:00:00" 34 parsedTime, err := time.Parse("2006-01-02 15:04:05", timeStr) 35 if err != nil { 36 fmt.Printf("解析时间错误:%v\n", err) 37 } else { 38 fmt.Printf("字符串时间转时间戳:%d\n", parsedTime.Unix()) 39 } 40 41 // 格式化当前时间 42 now := time.Now() 43 fmt.Printf("当前时间(标准格式):%s\n", now.Format("2006-01-02 15:04:05")) 44 fmt.Printf("当前时间(ISO格式):%s\n", now.Format(time.RFC3339)) 45 fmt.Printf("当前时间(中文格式):%s\n", now.Format("2006年01月02日 15时04分05秒")) 46 47 // 时间戳字符串转换 48 timestampStr := "1704067200" 49 timestampInt, err := strconv.ParseInt(timestampStr, 10, 64) 50 if err != nil { 51 fmt.Printf("解析时间戳字符串错误:%v\n", err) 52 } else { 53 dateFromStr := time.Unix(timestampInt, 0) 54 fmt.Printf("字符串时间戳转时间:%s\n", dateFromStr.Format("2006-01-02 15:04:05")) 55 } 56 57 // 获取时区信息 58 fmt.Printf("当前时区:%s\n", time.Now().Location().String()) 59 fmt.Printf("UTC时间:%s\n", time.Now().UTC().Format("2006-01-02 15:04:05")) 60 61 // 时间计算示例 62 oneHourLater := time.Now().Add(time.Hour) 63 fmt.Printf("一小时后的时间戳:%d\n", oneHourLater.Unix()) 64 65 oneDayLater := time.Now().AddDate(0, 0, 1) 66 fmt.Printf("一天后的时间戳:%d\n", oneDayLater.Unix()) 67}
-
获取时间戳 (JAVA)
1import java.time.*; 2import java.time.format.DateTimeFormatter; 3import java.util.Date; 4 5public class TimestampExample { 6 public static void main(String[] args) { 7 // 获取当前时间戳(毫秒级) 8 long currentTimestampMilliseconds = System.currentTimeMillis(); 9 System.out.println("当前时间戳(毫秒):" + currentTimestampMilliseconds); 10 11 // 获取当前时间戳(秒级) 12 long currentTimestampSeconds = System.currentTimeMillis() / 1000; 13 System.out.println("当前时间戳(秒):" + currentTimestampSeconds); 14 15 // 使用Instant获取时间戳 16 Instant now = Instant.now(); 17 System.out.println("当前时间戳(Instant):" + now.toEpochMilli()); 18 19 // 获取指定时间的时间戳 20 LocalDateTime specificTime = LocalDateTime.of(2024, 1, 1, 12, 0, 0); 21 long specificTimestamp = specificTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); 22 System.out.println("指定时间的时间戳(毫秒):" + specificTimestamp); 23 24 // 时间戳转换为时间 25 long timestamp = 1704067200000L; // 2024-01-01 12:00:00 26 Instant instant = Instant.ofEpochMilli(timestamp); 27 LocalDateTime dateFromTimestamp = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); 28 System.out.println("时间戳转时间:" + dateFromTimestamp.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); 29 30 // 字符串时间转换为时间戳 31 String timeStr = "2024-01-01 12:00:00"; 32 LocalDateTime parsedTime = LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); 33 long timestampFromStr = parsedTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); 34 System.out.println("字符串时间转时间戳:" + timestampFromStr); 35 36 // 格式化当前时间 37 LocalDateTime nowDateTime = LocalDateTime.now(); 38 System.out.println("当前时间(标准格式):" + nowDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); 39 System.out.println("当前时间(ISO格式):" + nowDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); 40 System.out.println("当前时间(中文格式):" + nowDateTime.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒"))); 41 42 // 时间戳字符串转换 43 String timestampStr = "1704067200000"; 44 long timestampInt = Long.parseLong(timestampStr); 45 LocalDateTime dateFromStr = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestampInt), ZoneId.systemDefault()); 46 System.out.println("字符串时间戳转时间:" + dateFromStr.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); 47 48 // 获取时区信息 49 System.out.println("当前时区:" + ZoneId.systemDefault()); 50 System.out.println("UTC时间:" + LocalDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); 51 52 // 时间计算示例 53 LocalDateTime oneHourLater = LocalDateTime.now().plusHours(1); 54 long oneHourLaterTimestamp = oneHourLater.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); 55 System.out.println("一小时后的时间戳:" + oneHourLaterTimestamp); 56 57 LocalDateTime oneDayLater = LocalDateTime.now().plusDays(1); 58 long oneDayLaterTimestamp = oneDayLater.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); 59 System.out.println("一天后的时间戳:" + oneDayLaterTimestamp); 60 61 // 使用Date类(传统方式) 62 Date currentDate = new Date(); 63 System.out.println("当前时间(Date):" + currentDate); 64 System.out.println("当前时间戳(Date):" + currentDate.getTime()); 65 66 // 时区转换示例 67 // 创建UTC时间 68 LocalDateTime utcTime = LocalDateTime.now(ZoneOffset.UTC); 69 System.out.println("UTC时间:" + utcTime); 70 71 // 转换为本地时间 72 LocalDateTime localTime = utcTime.atZone(ZoneOffset.UTC).withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime(); 73 System.out.println("本地时间:" + localTime); 74 75 // 创建特定时区时间(例如:东八区) 76 ZoneId chinaZone = ZoneId.of("Asia/Shanghai"); 77 LocalDateTime chinaTime = LocalDateTime.now(chinaZone); 78 System.out.println("中国时间:" + chinaTime); 79 80 // 时间差计算 81 LocalDateTime time1 = LocalDateTime.of(2024, 1, 1, 12, 0, 0); 82 LocalDateTime time2 = LocalDateTime.of(2024, 1, 2, 12, 0, 0); 83 Duration duration = Duration.between(time1, time2); 84 System.out.println("时间差(小时):" + duration.toHours()); 85 System.out.println("时间差(秒):" + duration.getSeconds()); 86 87 // 格式化时间戳为不同格式 88 long currentTime = System.currentTimeMillis(); 89 System.out.println("Unix时间戳(秒):" + currentTime / 1000); 90 System.out.println("Unix时间戳(毫秒):" + currentTime); 91 92 // 获取纳秒级精度 93 long nanoTime = System.nanoTime(); 94 System.out.println("纳秒时间:" + nanoTime); 95 } 96}
-
获取时间戳 (JS)
1// JavaScript 获取时间戳示例代码 2 3// 获取当前时间戳(毫秒级) 4function getCurrentTimestamp() { 5 return Date.now(); 6} 7 8// 获取当前时间戳(秒级) 9function getCurrentTimestampSeconds() { 10 return Math.floor(Date.now() / 1000); 11} 12 13// 获取指定时间的时间戳 14function getTimestampFromDate(dateString) { 15 return new Date(dateString).getTime(); 16} 17 18// 时间戳转换为日期 19function timestampToDate(timestamp) { 20 return new Date(timestamp); 21} 22 23// 格式化时间戳为可读字符串 24function formatTimestamp(timestamp) { 25 const date = new Date(timestamp); 26 return date.toLocaleString('zh-CN', { 27 year: 'numeric', 28 month: '2-digit', 29 day: '2-digit', 30 hour: '2-digit', 31 minute: '2-digit', 32 second: '2-digit' 33 }); 34} 35 36// 示例使用 37console.log('当前时间戳(毫秒):', getCurrentTimestamp()); 38console.log('当前时间戳(秒):', getCurrentTimestampSeconds()); 39 40const specificDate = '2024-01-01 12:00:00'; 41console.log('指定时间的时间戳:', getTimestampFromDate(specificDate)); 42 43const timestamp = 1704067200000; // 2024-01-01 12:00:00 44console.log('时间戳转日期:', timestampToDate(timestamp)); 45console.log('格式化时间戳:', formatTimestamp(timestamp)); 46 47// 获取当前时间的各种格式 48const now = new Date(); 49console.log('ISO格式:', now.toISOString()); 50console.log('本地格式:', now.toLocaleString()); 51console.log('UTC格式:', now.toUTCString());
-
获取时间戳 (PHP)
1<?php 2// PHP 获取时间戳示例代码 3 4// 获取当前时间戳(秒级) 5$current_timestamp_seconds = time(); 6echo "当前时间戳(秒):" . $current_timestamp_seconds . "\n"; 7 8// 获取当前时间戳(毫秒级) 9$current_timestamp_milliseconds = round(microtime(true) * 1000); 10echo "当前时间戳(毫秒):" . $current_timestamp_milliseconds . "\n"; 11 12// 获取当前时间戳(微秒级) 13$current_timestamp_microseconds = microtime(true); 14echo "当前时间戳(微秒):" . $current_timestamp_microseconds . "\n"; 15 16// 获取指定时间的时间戳 17$specific_time = mktime(12, 0, 0, 1, 1, 2024); 18echo "指定时间的时间戳(秒):" . $specific_time . "\n"; 19 20// 时间戳转换为时间 21$timestamp = 1704067200; // 2024-01-01 12:00:00 22$date_from_timestamp = date('Y-m-d H:i:s', $timestamp); 23echo "时间戳转时间:" . $date_from_timestamp . "\n"; 24 25// 字符串时间转换为时间戳 26$time_str = "2024-01-01 12:00:00"; 27$timestamp_from_str = strtotime($time_str); 28echo "字符串时间转时间戳:" . $timestamp_from_str . "\n"; 29 30// 格式化当前时间 31$now = date('Y-m-d H:i:s'); 32echo "当前时间(标准格式):" . $now . "\n"; 33echo "当前时间(ISO格式):" . date('c') . "\n"; 34echo "当前时间(中文格式):" . date('Y年m月d日 H时i分s秒') . "\n"; 35 36// 时间戳字符串转换 37$timestamp_str = "1704067200"; 38$timestamp_int = intval($timestamp_str); 39$date_from_str = date('Y-m-d H:i:s', $timestamp_int); 40echo "字符串时间戳转时间:" . $date_from_str . "\n"; 41 42// 获取时区信息 43echo "当前时区:" . date_default_timezone_get() . "\n"; 44echo "UTC时间:" . gmdate('Y-m-d H:i:s') . "\n"; 45 46// 时间计算示例 47$one_hour_later = time() + 3600; 48echo "一小时后的时间戳:" . $one_hour_later . "\n"; 49 50$one_day_later = time() + 86400; 51echo "一天后的时间戳:" . $one_day_later . "\n"; 52 53// 使用DateTime类(面向对象方式) 54$datetime = new DateTime(); 55echo "当前时间(DateTime):" . $datetime->format('Y-m-d H:i:s') . "\n"; 56echo "当前时间戳(DateTime):" . $datetime->getTimestamp() . "\n"; 57 58// 创建指定时间的DateTime对象 59$specific_datetime = new DateTime('2024-01-01 12:00:00'); 60echo "指定时间(DateTime):" . $specific_datetime->format('Y-m-d H:i:s') . "\n"; 61echo "指定时间戳(DateTime):" . $specific_datetime->getTimestamp() . "\n"; 62 63// 时间戳转换为DateTime对象 64$timestamp_for_datetime = 1704067200; 65$datetime_from_timestamp = new DateTime(); 66$datetime_from_timestamp->setTimestamp($timestamp_for_datetime); 67echo "时间戳转DateTime:" . $datetime_from_timestamp->format('Y-m-d H:i:s') . "\n"; 68 69// 时区转换示例 70// 设置时区为UTC 71$utc_datetime = new DateTime('now', new DateTimeZone('UTC')); 72echo "UTC时间:" . $utc_datetime->format('Y-m-d H:i:s') . "\n"; 73 74// 设置时区为中国时区 75$china_datetime = new DateTime('now', new DateTimeZone('Asia/Shanghai')); 76echo "中国时间:" . $china_datetime->format('Y-m-d H:i:s') . "\n"; 77 78// 时间差计算 79$time1 = new DateTime('2024-01-01 12:00:00'); 80$time2 = new DateTime('2024-01-02 12:00:00'); 81$interval = $time1->diff($time2); 82echo "时间差:" . $interval->format('%d天 %h小时 %i分钟 %s秒') . "\n"; 83 84// 使用DateInterval进行时间计算 85$now_datetime = new DateTime(); 86$one_hour_later_datetime = clone $now_datetime; 87$one_hour_later_datetime->add(new DateInterval('PT1H')); 88echo "一小时后的时间:" . $one_hour_later_datetime->format('Y-m-d H:i:s') . "\n"; 89 90$one_day_later_datetime = clone $now_datetime; 91$one_day_later_datetime->add(new DateInterval('P1D')); 92echo "一天后的时间:" . $one_day_later_datetime->format('Y-m-d H:i:s') . "\n"; 93 94// 格式化时间戳为不同格式 95$current_time = time(); 96echo "Unix时间戳(秒):" . $current_time . "\n"; 97echo "Unix时间戳(毫秒):" . round(microtime(true) * 1000) . "\n"; 98 99// 获取各种时间格式 100echo "当前时间(RFC 2822):" . date('r') . "\n"; 101echo "当前时间(RFC 3339):" . date('c') . "\n"; 102echo "当前时间(ISO 8601):" . date('Y-m-d\TH:i:sO') . "\n"; 103 104// 使用strftime函数(已弃用,但仍在某些环境中可用) 105if (function_exists('strftime')) { 106 echo "当前时间(strftime):" . strftime('%Y-%m-%d %H:%M:%S') . "\n"; 107} 108 109// 获取时间戳的不同精度 110echo "微秒时间戳:" . microtime() . "\n"; 111echo "微秒时间戳(浮点数):" . microtime(true) . "\n"; 112 113// 时区相关操作 114$timezone_list = DateTimeZone::listIdentifiers(); 115echo "可用时区数量:" . count($timezone_list) . "\n"; 116 117// 设置默认时区 118date_default_timezone_set('Asia/Shanghai'); 119echo "设置后的时区:" . date_default_timezone_get() . "\n"; 120echo "设置后的时间:" . date('Y-m-d H:i:s') . "\n"; 121?>
-
获取时间戳 (PY)
1import time 2import datetime 3from datetime import timezone, timedelta 4 5# 获取当前时间戳(秒级) 6current_timestamp_seconds = int(time.time()) 7print(f"当前时间戳(秒):{current_timestamp_seconds}") 8 9# 获取当前时间戳(毫秒级) 10current_timestamp_milliseconds = int(time.time() * 1000) 11print(f"当前时间戳(毫秒):{current_timestamp_milliseconds}") 12 13# 获取当前时间戳(微秒级) 14current_timestamp_microseconds = int(time.time() * 1000000) 15print(f"当前时间戳(微秒):{current_timestamp_microseconds}") 16 17# 获取指定时间的时间戳 18specific_time = datetime.datetime(2024, 1, 1, 12, 0, 0) 19specific_timestamp = int(specific_time.timestamp()) 20print(f"指定时间的时间戳(秒):{specific_timestamp}") 21 22# 时间戳转换为时间 23timestamp = 1704067200 # 2024-01-01 12:00:00 24date_from_timestamp = datetime.datetime.fromtimestamp(timestamp) 25print(f"时间戳转时间:{date_from_timestamp.strftime('%Y-%m-%d %H:%M:%S')}") 26 27# 字符串时间转换为时间戳 28time_str = "2024-01-01 12:00:00" 29parsed_time = datetime.datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S") 30timestamp_from_str = int(parsed_time.timestamp()) 31print(f"字符串时间转时间戳:{timestamp_from_str}") 32 33# 格式化当前时间 34now = datetime.datetime.now() 35print(f"当前时间(标准格式):{now.strftime('%Y-%m-%d %H:%M:%S')}") 36print(f"当前时间(ISO格式):{now.isoformat()}") 37print(f"当前时间(中文格式):{now.strftime('%Y年%m月%d日 %H时%M分%S秒')}") 38 39# 时间戳字符串转换 40timestamp_str = "1704067200" 41timestamp_int = int(timestamp_str) 42date_from_str = datetime.datetime.fromtimestamp(timestamp_int) 43print(f"字符串时间戳转时间:{date_from_str.strftime('%Y-%m-%d %H:%M:%S')}") 44 45# 获取时区信息 46print(f"当前时区:{datetime.datetime.now().astimezone().tzinfo}") 47print(f"UTC时间:{datetime.datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')}") 48 49# 时间计算示例 50one_hour_later = datetime.datetime.now() + timedelta(hours=1) 51print(f"一小时后的时间戳:{int(one_hour_later.timestamp())}") 52 53one_day_later = datetime.datetime.now() + timedelta(days=1) 54print(f"一天后的时间戳:{int(one_day_later.timestamp())}") 55 56# 使用time模块的其他功能 57print(f"时间元组:{time.localtime()}") 58print(f"格式化时间:{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}") 59 60# 时区转换示例 61# 创建UTC时间 62utc_time = datetime.datetime.now(timezone.utc) 63print(f"UTC时间:{utc_time}") 64 65# 转换为本地时间 66local_time = utc_time.astimezone() 67print(f"本地时间:{local_time}") 68 69# 创建特定时区时间(例如:东八区) 70china_tz = timezone(timedelta(hours=8)) 71china_time = datetime.datetime.now(china_tz) 72print(f"中国时间:{china_time}") 73 74# 时间差计算 75time1 = datetime.datetime(2024, 1, 1, 12, 0, 0) 76time2 = datetime.datetime(2024, 1, 2, 12, 0, 0) 77time_diff = time2 - time1 78print(f"时间差:{time_diff}") 79print(f"时间差(秒):{time_diff.total_seconds()}")