简体   繁体   English

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

[英]How to convert current date to epoch timestamp?

How to convert current date to epoch timestamp ?如何将当前日期转换为纪元时间戳?

Format current date:格式化当前日期:

29.08.2011 11:05:02

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

Your code will behave strange if 'TZ' is not set properly, eg 'UTC' or 'Asia/Kolkata'如果 'TZ' 设置不正确,您的代码会表现得很奇怪,例如 'UTC' 或 'Asia/Kolkata'

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

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"));
import time
def expires():
    '''return a UNIX style timestamp representing 5 minutes from now'''
    return int(time.time()+300)
from time import time
>>> int(time())
1542449530


>>> time()
1542449527.6991141
>>> int(time())
1542449530
>>> str(time()).replace(".","")
'154244967282'

But Should it not return ?但它不应该返回吗?

'15424495276991141'

if you want UTC try some of the gm functions:如果你想要 UTC 尝试一些gm功能:

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

使用strptime解析时间,并对其调用time()以获取 Unix 时间戳。

在此处输入图片说明 I think this answer needs an update and the solution would go better this way.我认为这个答案需要更新,这样解决方案会更好。

from datetime import datetime

datetime.strptime("29.08.2011 11:05:02", "%d.%m.%Y %H:%M:%S").strftime("%s")

or you may use datetime object and format the time using %s to convert it into epoch time.或者您可以使用 datetime 对象并使用 %s 格式化时间以将其转换为纪元时间。

Short-hand to convert python date/datetime to Epoch (without microseconds)短手转换蟒蛇日期/日期时间到时代(无微秒)

int(current_date.strftime("%s")) # 2020-01-14  ---> 1578956400
int(current_datetime.strftime("%s")) # 2020-01-14 16:59:30.251176 -----> 1579017570

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM