python各种语言间时间的转化实现代码

yipeiwu_com5年前Python基础

一 基本知识

millisecond 毫秒
microsecond 微秒
nanosecond 纳秒
1秒=1000毫秒 1毫秒=1000微秒 1微秒=1000纳秒

二 perl

perl中可以使用time或localtime来获得时间,time返回从1970年1月1日0点的秒数,localtime返回当前时间的字符串表示,或者年月日等得tuple表示。

#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw(strftime);

# seconds from 1970.01.01 00:00:00
my $ti = time();
print $ti;
print "\n";
print strftime("%Y-%m-%d %H:%M:%S\n", localtime($ti));
#1310623469
#2011-07-14 14:03:58

my $t = localtime();
print $t;
print "\n";
#Thu Jul 14 12:25:16 2011

my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst)=localtime();
print $year;
print "\n";
#111

print strftime("%Y-%m-%d %H:%M:%S\n", localtime());
#2011-07-14 12:26:01

三 c#
1tick = 100 nanosecond

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyTest
{
  class Program
  {
    static void DateTimeTest()
    {
      DateTime dt2 = DateTime.Now;
      Console.WriteLine(dt2.Ticks);
      Console.WriteLine(dt2.ToString("MM/dd/yyyy hh:mm:ss"));
    }

    static DateTime? ConvertPerlTimeToDateTime(string perltime)
    {
      DateTime? dt = null;
      //perl time variable : seconds from 1970.01.01 00:00:00 
      string sdt = perltime;
      long ldt = 0;
      if (long.TryParse(sdt, out ldt))
      {
        long ldt2 = new DateTime(1970, 1, 1).Ticks + ldt * 1000 * 1000 * 10;
         dt = new DateTime(ldt2, DateTimeKind.Local);
        Console.WriteLine(dt.Value.ToString("MM/dd/yyyy hh:mm:ss"));
      }
      return dt;
    }

    static void Main(string[] args)
    {
      DateTimeTest();
      ConvertPerlTimeToDateTime("1309423883");
      //634462479788396720
      //07/14/2011 01:46:18
      //06/30/2011 08:51:23
    }
  }
}

四 python

python的perl相似,time也是从1970年1月1日开始的秒数。

import time

ISOTIMEFORMAT='%Y-%m-%d %X'

# seconds from 1970.01.01 00:00:00
t = time.time()
print (t)
print time.strftime(ISOTIMEFORMAT,time.localtime(t))
#1310623143.12
#2011-07-14 13:59:03

(year,mon,day,hour,min,sec,wday,yday,isdst) = time.localtime()
print (year)
print (time.strftime(ISOTIMEFORMAT, time.localtime()))
#2011
#2011-07-14 13:59:03

相关文章

Python面向对象程序设计之私有属性及私有方法示例

本文实例讲述了Python面向对象程序设计之私有属性及私有方法。分享给大家供大家参考,具体如下: 如果有一个对象,当需要对其进行修改属性时,有2种方法: (1)对象名.属性名=数据---...

python 列表推导式使用详解

所谓的列表推导式,就是指的轻量级循环创建列表。 基本使用方式 # 创建一个0-10的列表 a = [x for x in range(11)] print(a) """ 输出结果:...

完美解决Python matplotlib绘图时汉字显示不正常的问题

完美解决Python matplotlib绘图时汉字显示不正常的问题

Matplotlib是一个很好的作图软件,但是python下默认不支持中文,所以需要做一些修改,方法如下: 1.在python安装目录的Lib目录下创建ch.py文件。 文件中代码为:...

python中while和for的区别总结

Python中for循环和while循环本质上是没有区别的,但是在实际应用上,针对性不太一样。 while循环适用于未知循环次数的循环,for循环适用于已知循环次数的循环 。 for主...

为Python的Tornado框架配置使用Jinja2模板引擎的方法

tornado 默认有一个模板引擎但是功能简单(其实我能用到的都差不多)使用起来颇为麻烦, 而jinja2语法与django模板相似所以决定使用他. 下载jinja2 还是用pip 下载...