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的GIL

一篇文章快速了解Python的GIL

前言:博主在刚接触Python的时候时常听到GIL这个词,并且发现这个词经常和Python无法高效的实现多线程划上等号。本着不光要知其然,还要知其所以然的研究态度,博主搜集了各方面的资料...

selenium+python自动化测试之环境搭建

selenium+python自动化测试之环境搭建

最近由于公司有一个向谷歌网站上传文件的需求,需要进行web的自动化测试,选择了selenium这个自动化测试框架,以前没有接触过这门技术,所以研究了一下,使用python来实现自动化脚本...

Python网页解析利器BeautifulSoup安装使用介绍

Python网页解析利器BeautifulSoup安装使用介绍

python解析网页,无出BeautifulSoup左右,此是序言 安装 BeautifulSoup4以后的安装需要用eazy_install,如果不需要最新的功能,安装版本3就够了,千...

简单了解python字符串前面加r,u的含义

简单了解python字符串前面加r,u的含义

这篇文章主要介绍了简单了解python字符串前面加r,u的含义,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 u/U:表示unicod...

浅谈django orm 优化

orm优化 1.数据库技术进行优化,包括给字段加索引,设置唯一性约束等等; 2.查询过滤工作在数据库语句中做,不要放在代码中完成(看情况); 3.如果要一次查询出集合的数量,使用c...