以毫秒为单位将date时间格式化为string

我想从毫秒的date有一个datetimestring。 这个代码对我来说是典型的,我渴望学习如何缩短它。

 from datetime import datetime timeformatted= str(datetime.utcnow()) semiformatted= timeformatted.replace("-","") almostformatted= semiformatted.replace(":","") formatted=almostformatted.replace(".","") withspacegoaway=formatted.replace(" ","") formattedstripped=withspacegoaway.strip() print formattedstripped 

10 Solutions collect form web for “以毫秒为单位将date时间格式化为string”

要获得一个毫秒数字(小数点后三位)的datestring,使用这个:

 from datetime import datetime print datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] >>>> OUTPUT >>>> 2017-10-04 10:18:32.926 
 print datetime.utcnow().strftime('%Y%m%d%H%M%S%f') 

http://docs.python.org/library/datetime.html#strftime-strptime-behavior

@Cabbi提出的问题是,在某些系统上,微秒格式%f可能会给出"0" ,所以不能简单地将最后三个字符砍掉。

下面的代码仔细格式化一个毫秒的时间戳:

 from datetime import datetime (dt, micro) = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f').split('.') dt = "%s.%03d" % (dt, int(micro) / 1000) print dt 

输出示例:

 2016-02-26 04:37:53.133 

为了得到OP所需的确切输出,我们必须去掉标点符号:

 from datetime import datetime (dt, micro) = datetime.utcnow().strftime('%Y%m%d%H%M%S.%f').split('.') dt = "%s%03d" % (dt, int(micro) / 1000) print dt 

输出示例:

 20160226043839901 

我假设你的意思是你正在寻找比datetime.datetime.strftime()更快的东西,并且实际上是从utc时间戳中去除了非alpha字符。

你的方法是稍微快一点,我想你可以通过切分string来加快速度:

 >>> import timeit >>> t=timeit.Timer('datetime.utcnow().strftime("%Y%m%d%H%M%S%f")',''' ... from datetime import datetime''') >>> t.timeit(number=10000000) 116.15451288223267 >>> def replaceutc(s): ... return s\ ... .replace('-','') \ ... .replace(':','') \ ... .replace('.','') \ ... .replace(' ','') \ ... .strip() ... >>> t=timeit.Timer('replaceutc(str(datetime.datetime.utcnow()))',''' ... from __main__ import replaceutc ... import datetime''') >>> t.timeit(number=10000000) 77.96774983406067 >>> def sliceutc(s): ... return s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:] ... >>> t=timeit.Timer('sliceutc(str(datetime.utcnow()))',''' ... from __main__ import sliceutc ... from datetime import datetime''') >>> t.timeit(number=10000000) 62.378515005111694 
 from datetime import datetime from time import clock t = datetime.utcnow() print 't == %s %s\n\n' % (t,type(t)) n = 100000 te = clock() for i in xrange(1): t_stripped = t.strftime('%Y%m%d%H%M%S%f') print clock()-te print t_stripped," t.strftime('%Y%m%d%H%M%S%f')" print te = clock() for i in xrange(1): t_stripped = str(t).replace('-','').replace(':','').replace('.','').replace(' ','') print clock()-te print t_stripped," str(t).replace('-','').replace(':','').replace('.','').replace(' ','')" print te = clock() for i in xrange(n): t_stripped = str(t).translate(None,' -:.') print clock()-te print t_stripped," str(t).translate(None,' -:.')" print te = clock() for i in xrange(n): s = str(t) t_stripped = s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:] print clock()-te print t_stripped," s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:] " 

结果

 t == 2011-09-28 21:31:45.562000 <type 'datetime.datetime'> 3.33410112179 20110928212155046000 t.strftime('%Y%m%d%H%M%S%f') 1.17067364707 20110928212130453000 str(t).replace('-','').replace(':','').replace('.','').replace(' ','') 0.658806915404 20110928212130453000 str(t).translate(None,' -:.') 0.645189262881 20110928212130453000 s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:] 

使用translate()切片方法在同一时间运行
translate()提供了在一行中可用的优点

比较在第一个基础上的时间:

1.000 * t.strftime('%Y%m%d%H%M%S%f')

replace('','')。replace('。','')。replace('','')。

0.198 * str(t).translate(None,' – :')

0.194 * s [:4] + s [5:7] + s [8:10] + s [11:13] + s [14:16] + s [17:19] + s [20:]

可能是这样的:

 import datetime now = datetime.datetime.now() now.strftime('%Y/%m/%d %H:%m:%S.%f')[:-3] # [:-3] => Removing the 3 last characters as %f is for microsecs. 

我处理了同样的问题,但在我的情况下,重要的是,毫秒是舍入,而不是截断

 from datetime import datetime, timedelta def strftime_ms(datetime_obj): y,m,d,H,M,S = datetime_obj.timetuple()[:6] ms = timedelta(microseconds = round(datetime_obj.microsecond/1000.0)*1000) ms_date = datetime(y,m,d,H,M,S) + ms return ms_date.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] 
 import datetime # convert string into date time format. str_date = '2016-10-06 15:14:54.322989' d_date = datetime.datetime.strptime(str_date , '%Y-%m-%d %H:%M:%S.%f') print(d_date) print(type(d_date)) # check d_date type. # convert date time to regular format. reg_format_date = d_date.strftime("%d %B %Y %I:%M:%S %p") print(reg_format_date) # some other date formats. reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p") print(reg_format_date) reg_format_date = d_date.strftime("%Y-%m-%d %H:%M:%S") print(reg_format_date) 

<<<<<<输出>>>>>>>

 2016-10-06 15:14:54.322989 <class 'datetime.datetime'> 06 October 2016 03:14:54 PM 2016-10-06 03:14:54 PM 2016-10-06 15:14:54 
 python -c "from datetime import datetime; print str(datetime.now())[:-3]" 2017-02-09 10:06:37.006 

只需使用datetime.datetime.strftime()和适当的格式string即可。

  • 在python中将string转换为二进制
  • 在Java中,如何检查一个string是否包含子string(忽略大小写)?
  • 如何连接NSIS中的2个string
  • 如何在Java中分割string
  • Java String.split是否有可能返回一个空的String
  • 任意长度的string的Python numpy数组
  • JavaScript中的string文字和string对象有什么区别?
  • 将查询string参数添加到link_to
  • swift如何删除可选的string字符
  • C#不会在开头附近编译一个长度为\ 0的常量string
  • 如何定义一个string值的枚举?