Python 或 JavaScript 生成当前时间戳

Python

# coding=utf-8
import time
import sys


def func():
    # 格式化输出时间
    s1 = int(time.strftime("%Y%m%d%H%M%S", time.localtime()))
    # 时间戳,由于默认是秒需要转换为毫秒输出
    s2 = int(round(time.time() * 1000))
    return s1, s2


def once():
    '''如果没有指明命令行参数则运行一次'''
    s1, s2 = func()
    print(s1)
    print(s2)


def main():
    args = sys.argv # 获取命令行参数
    if len(args) > 1:
        count = args[1]
        # 命令行参数为数字,则生成指定数量的时间戳
        if count.isdigit() and int(count) > 1:
            s1, s2 = func() # 元组解构
            # 按参数指定的次数递增时间
            for i in range(int(count)):
                print(s1 + i)
                print(s2 + i)
        else:
            once()
    else:
        once()


if __name__ == "__main__":
    main()

按指定次数生成,在命令行中执行,如下命令是指定生成10个

python app.py 10

JavaScript(NodeJS)

这段代码只能使用NodeJS环境来运行,需要先安装NodeJS

function func() {
    const dt = new Date();
    // 按年月日时分秒的顺序存入数组
    const source = [dt.getFullYear(), dt.getMonth() + 1, dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds()];
    let t = source[0];
    // 第一位为年份,从月份开始拼接时间数字,月份、天数、小时等如果是一位数字,会补上0,保证显示为两位
    for (let i = 1; i < source.length; i++) {
        const element = source[i];
        t = t * 100 + element;
    }
    // Date.now为Date对象的静态方法,可以直接获取到时间戳
    return [t, Date.now()]; // 返回的是一个数组,第一个为年月日时分秒的数字,第二个为时间戳
}

/*
如果没有指明命令行参数则运行一次
*/
function once() {
    const [s1, s2] = func();
    console.log(s1);
    console.log(s2);
}

// NodeJS中获取命令行参数(process.argv)
// 若要在普通的JS环境中运行(如浏览器),需要去掉对这个特殊变量(process.argv)的处理
const args = process.argv;
if (args.length > 2) {
    const len = Number(args[2]);
    if (!isNaN(len) && len > 1) {
        let [s1, s2] = func(); // 数组解构
        // 根据命令行参数指定的次数来生成多个时间戳,递增
        for (let i = 0; i < len; i++) {
            console.log(s1 + i);
            console.log(s2 + i);
        }
    } else {
        once();
    }
} else {
    once();
}

按指定次数生成,在命令行中执行,如下命令是指定生成10个

node app.js 10

如果能看到最后,或对你有帮助的话,欢迎在评论区留言一起交流。

posted @ 2020-08-04 16:19  DerWald  阅读(721)  评论(0)    收藏  举报