Python时间,日期,时间戳之间转换
来源:互联网 发布:最优化书籍推荐 编辑:程序博客网 时间:2024/05/17 01:02
http://www.2cto.com/kf/201401/276088.html
1
.将字符串的时间转换为时间戳
方法:
a =
"2013-10-10 23:40:00"
将其转换为时间数组
import
time
timeArray = time.strptime(a,
"%Y-%m-%d %H:%M:%S"
)
转换为时间戳:
timeStamp =
int
(time.mktime(timeArray))
timeStamp ==
1381419600
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
2
.字符串格式更改
如a =
"2013-10-10 23:40:00"
,想改为 a =
"2013/10/10 23:40:00"
方法:先转换为时间数组,然后转换为其他格式
timeArray = time.strptime(a,
"%Y-%m-%d %H:%M:%S"
)
otherStyleTime = time.strftime(
"%Y/%m/%d %H:%M:%S"
, timeArray)
3
.时间戳转换为指定格式日期:
方法一:
利用localtime()转换为时间数组,然后格式化为需要的格式,如
timeStamp =
1381419600
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime(
"%Y-%m-%d %H:%M:%S"
, timeArray)
otherStyletime ==
"2013-10-10 23:40:00"
方法二:
import
datetime
timeStamp =
1381419600
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
otherStyleTime = dateArray.strftime(
"%Y-%m-%d %H:%M:%S"
)
otherStyletime ==
"2013-10-10 23:40:00"
4
.获取当前时间并转换为指定日期格式
方法一:
import
time
获得当前时间时间戳
now =
int
(time.time()) ->这是时间戳
转换为其他日期格式,如:
"%Y-%m-%d %H:%M:%S"
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime(
"%Y-%m-%d %H:%M:%S"
, timeArray)
方法二:
import
datetime
获得当前时间
now = datetime.datetime.now() ->这是时间数组格式
转换为指定的格式:
otherStyleTime = now.strftime(
"%Y-%m-%d %H:%M:%S"
)
5
.获得三天前的时间
方法:
import
time
import
datetime
先获得时间数组格式的日期
threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days =
3
))
转换为时间戳:
timeStamp =
int
(time.mktime(threeDayAgo.timetuple()))
转换为其他字符串格式:
otherStyleTime = threeDayAgo.strftime(
"%Y-%m-%d %H:%M:%S"
)
注:timedelta()的参数有:days,hours,seconds,microseconds
6
.给定时间戳,计算该时间的几天前时间:
timeStamp =
1381419600
先转换为datetime
import
datetime
import
time
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
threeDayAgo = dateArray - datetime.timedelta(days =
3
)
参考
5
,可以转换为其他的任意格式了
0 0
- Python时间,日期,时间戳之间转换
- Python时间,日期,时间戳之间转换
- Python时间,日期,时间戳之间转换
- Python时间,日期,时间戳之间转换
- Python时间,日期,时间戳之间转换
- Python时间,日期,时间戳之间转换
- Python时间,日期,时间戳之间转换
- Python时间,日期,时间戳之间转换
- python中时间、日期、时间戳之间的转换
- python时间日期转换
- 日期与时间戳之间相互转换
- 时间戳标准日期之间的转换
- python转换时间戳和日期时间格式的转换
- python时间戳和日期转换
- Python 时间戳和日期相互转换
- python日期时间字符串转换成unix时间戳
- python日期时间字符串转换成unix时间戳
- python日期时间字符串转换成unix时间戳
- androidstudio快捷键-不断完善版
- 音频功放的另一个mono接法
- segment如何添加方法
- c# 使用初始化器初始化对象
- Android SDK开发包国内下载地址
- Python时间,日期,时间戳之间转换
- 三种Java查找算法
- 求无向联通图的割点
- ReactiveCocoa,最受欢迎的iOS函数响应式编程库(2.5版),没有之一!
- 为什么微软Edge浏览器得不到用户的喜爱
- 算法题 子数组之和为零
- 工作日志-20151019
- eclipse一些问题点归纳整理
- 黑马程序员--Java学习日记之IO流(字符流和字节流)