0%

Python 日期格式,时间戳之间转换

获取当前时间戳

  • 方法:
1
2
3
4
5
import time


now = time.time()
print('now:', now, '\n', type(now))
  • 输出结果:
1
2
now: 1498926743.1411922 
<class 'float'>

获取当前日期

  • 方法:
1
2
3
4
5
import datetime


datenow = datetime.datetime.now()
print('datenow:', datenow, '\n', type(datenow))
  • 输出结果:
1
2
datenow: 2017-07-02 00:34:35.272749 
<class 'datetime.datetime'>

字符串格式更改

如a = “2017-07-02 00:34:35”,想改为 a = “2017/07/02 00:34:35”

  • 方法:
1
2
3
4
5
6
7
import time


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) # 转换为其他格式
print('otherStyleTime:', otherStyleTime)
  • 输出结果:
1
otherStyleTime: 2017/07/02 00:34:35

将字符串的时间转换为时间戳

  • 方法:
1
2
3
4
5
6
7
import time


a = "2017-07-02 00:34:35"
timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S") # 将其转换为时间数组
timeStamp = int(time.mktime(timeArray)) # 转换为时间戳
print('timesStamp:', timeStamp)
  • 输出结果:
1
timesStamp: 1498926875

时间戳转换为指定格式日期

  • 方法一:
1
2
3
4
5
6
7
import time


timeStamp = 1498927046
timeArray = time.localtime(timeStamp) # 利用localtime()转换为时间数组
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) # 格式化为需要的格式
print('otherStyleTime:', otherStyleTime)
  • 方法二:
1
2
3
4
5
6
7
import datetime


timeStamp = 1498927046
dateArray = datetime.datetime.fromtimestamp(timeStamp)
otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
print('otherStyleTime:', otherStyleTime)
  • 输出结果:
1
otherStyleTime: 2017-07-02 00:37:26

获取当前时间并转换为指定日期格式

  • 方法一:
1
2
3
4
5
6
7
import time


now = int(time.time()) # 获得当前时间时间戳
timeArray = time.localtime(now)
StyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print('StyleTime:', StyleTime)
  • 方法二:
1
2
3
4
5
6
import datetime


now = datetime.datetime.now() # 获得当前时间,这是时间数组格式
StyleTime = now.strftime("%Y-%m-%d %H:%M:%S") # 转换为指定的格式
print('StyleTime:', StyleTime)
  • 输出结果:
1
StyleTime: 2017-07-02 00:16:30

获得三天前的时间

  • 方法:
1
2
3
4
5
6
7
8
import time
import datetime


threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 3)) # 先获得时间数组格式的日期
timeStamp = int(time.mktime(threeDayAgo.timetuple())) # 转换为时间戳
threeDayAgo = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S") # 转换为其他字符串格式
print('threeDayAgo:', threeDayAgo)

timedelta()的参数有:days, seconds, microseconds, milliseconds, minutes, hours, weeks

  • 输出结果:
1
threeDayAgo: 2017-06-29 00:21:04

给定时间戳,计算该时间的几天前时间:

  • 方法:
1
2
3
4
5
6
7
import datetime


timeStamp = 1498926852
dateArray = datetime.datetime.fromtimestamp(timeStamp) # 先转换为datetime
threeDayAgo = dateArray - datetime.timedelta(days=3)
print('threeDayAgo:', threeDayAgo)
  • 输出结果:
1
threeDayAgo: 2017-06-28 16:34:12

参考上面,可以转换为其他的任意格式