如何将当前日期转换为历元时间戳?

时间:2021-12-30 16:03:20

How to convert current date to epoch timestamp ?

如何将当前日期转换为epoch时间戳?

Format current date:

当前日期格式:

29.08.2011 11:05:02

6 个解决方案

#1


76  

That should do it

应该做它

import time

date_time = '29.08.2011 11:05:02'
pattern = '%d.%m.%Y %H:%M:%S'
epoch = int(time.mktime(time.strptime(date_time, pattern)))
print epoch

#2


12  

Assuming you are using a 24 hour time format:

假设你使用的是24小时的时间格式:

import time;
t = time.mktime(time.strptime("29.08.2011 11:05:02", "%d.%m.%Y %H:%M:%S"));

#3


12  

Your code will behave strange if 'TZ' is not set properly, e.g. 'UTC' or 'Asia/Kolkata'

如果没有正确地设置“TZ”,你的代码会表现得很奇怪。“UTC”或“亚洲/加尔各答的

So, you need to do below

所以,你需要在下面做。

>>> import time, os
>>> d='2014-12-11 00:00:00'
>>> p='%Y-%m-%d %H:%M:%S'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch
1418236200
>>> os.environ['TZ']='UTC'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch
1418256000

#4


5  

import time
def expires():
    '''return a UNIX style timestamp representing 5 minutes from now'''
    return int(time.time()+300)

#5


2  

Use strptime to parse the time, and call time() on it to get the Unix timestamp.

使用strptime来解析时间,并调用time()来获得Unix时间戳。

#6


2  

if you want UTC try some of the gm functions:

如果您想要UTC,请尝试一些通用功能:

import time
import calendar

date_time = '29.08.2011 11:05:02'
pattern = '%d.%m.%Y %H:%M:%S'
utc_epoch = calendar.timegm(time.strptime(date_time, pattern))
print utc_epoch

#1


76  

That should do it

应该做它

import time

date_time = '29.08.2011 11:05:02'
pattern = '%d.%m.%Y %H:%M:%S'
epoch = int(time.mktime(time.strptime(date_time, pattern)))
print epoch

#2


12  

Assuming you are using a 24 hour time format:

假设你使用的是24小时的时间格式:

import time;
t = time.mktime(time.strptime("29.08.2011 11:05:02", "%d.%m.%Y %H:%M:%S"));

#3


12  

Your code will behave strange if 'TZ' is not set properly, e.g. 'UTC' or 'Asia/Kolkata'

如果没有正确地设置“TZ”,你的代码会表现得很奇怪。“UTC”或“亚洲/加尔各答的

So, you need to do below

所以,你需要在下面做。

>>> import time, os
>>> d='2014-12-11 00:00:00'
>>> p='%Y-%m-%d %H:%M:%S'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch
1418236200
>>> os.environ['TZ']='UTC'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch
1418256000

#4


5  

import time
def expires():
    '''return a UNIX style timestamp representing 5 minutes from now'''
    return int(time.time()+300)

#5


2  

Use strptime to parse the time, and call time() on it to get the Unix timestamp.

使用strptime来解析时间,并调用time()来获得Unix时间戳。

#6


2  

if you want UTC try some of the gm functions:

如果您想要UTC,请尝试一些通用功能:

import time
import calendar

date_time = '29.08.2011 11:05:02'
pattern = '%d.%m.%Y %H:%M:%S'
utc_epoch = calendar.timegm(time.strptime(date_time, pattern))
print utc_epoch