标签归档:strftime

在Python中将%f与strftime()结合使用可获取微秒

问题:在Python中将%f与strftime()结合使用可获取微秒

我想使用的strftime()以微秒级精度,这似乎可以使用%F(为说明这里)。但是,当我尝试以下代码时:

import time
import strftime from time

print strftime("%H:%M:%S.%f")

…我得到小时,分钟和秒,但%f打印为%f,没有微秒的迹象。我在Ubuntu上运行Python 2.6.5,所以应该没问题,应该支持%f(据我所知,它在2.6及更高版本中受支持。)

I’m trying to use strftime() to microsecond precision, which seems possible using %f (as stated here). However when I try the following code:

import time
import strftime from time

print strftime("%H:%M:%S.%f")

…I get the hour, the minutes and the seconds, but %f prints as %f, with no sign of the microseconds. I’m running Python 2.6.5 on Ubuntu, so it should be fine and %f should be supported (it’s supported for 2.6 and above, as far as I know.)


回答 0

您可以使用datetime的strftime函数来获取此信息。问题在于时间的strftime接受不携带微秒信息的时间元组。

from datetime import datetime
datetime.now().strftime("%H:%M:%S.%f")

应该做的把戏!

You can use datetime’s strftime function to get this. The problem is that time’s strftime accepts a timetuple that does not carry microsecond information.

from datetime import datetime
datetime.now().strftime("%H:%M:%S.%f")

Should do the trick!


回答 1

您正在查看错误的文档。该time模块具有不同的文档

您可以像这样使用datetime模块strftime

>>> from datetime import datetime
>>>
>>> now = datetime.now()
>>> now.strftime("%H:%M:%S.%f")
'12:19:40.948000'

You are looking at the wrong documentation. The time module has different documentation.

You can use the datetime module strftime like this:

>>> from datetime import datetime
>>>
>>> now = datetime.now()
>>> now.strftime("%H:%M:%S.%f")
'12:19:40.948000'

回答 2

使用Python的time模块,您无法获得毫秒%f

对于那些仍然只想使用time模块的人,这里有一个解决方法:

now = time.time()
mlsec = repr(now).split('.')[1][:3]
print time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), time.localtime(now))

您应该会得到类似2017-01-16 16:42:34.625 EET的信息(是的,我使用毫秒,因为这已经足够了)。

要将代码分成细节,请将以下代码粘贴到Python控制台中:

import time

# Get current timestamp
now = time.time()

# Debug now
now
print now
type(now)

# Debug strf time
struct_now = time.localtime(now)
print struct_now
type(struct_now)

# Print nicely formatted date
print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)

# Get miliseconds
mlsec = repr(now).split('.')[1][:3]
print mlsec

# Get your required timestamp string
timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)
print timestamp

为了澄清起见,我还在这里粘贴了Python 2.7.12结果:

>>> import time
>>> # get current timestamp
... now = time.time()
>>> # debug now
... now
1484578293.519106
>>> print now
1484578293.52
>>> type(now)
<type 'float'>
>>> # debug strf time
... struct_now = time.localtime(now)
>>> print struct_now
time.struct_time(tm_year=2017, tm_mon=1, tm_mday=16, tm_hour=16, tm_min=51, tm_sec=33, tm_wday=0, tm_yday=16, tm_isdst=0)
>>> type(struct_now)
<type 'time.struct_time'>
>>> # print nicely formatted date
... print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)
2017-01-16 16:51:33 EET
>>> # get miliseconds
... mlsec = repr(now).split('.')[1][:3]
>>> print mlsec
519
>>> # get your required timestamp string
... timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)
>>> print timestamp
2017-01-16 16:51:33.519 EET
>>>

With Python’s time module you can’t get microseconds with %f.

For those who still want to go with time module only, here is a workaround:

now = time.time()
mlsec = repr(now).split('.')[1][:3]
print time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), time.localtime(now))

You should get something like 2017-01-16 16:42:34.625 EET (yes, I use milliseconds as it’s fairly enough).

To break the code into details, paste the below code into a Python console:

import time

# Get current timestamp
now = time.time()

# Debug now
now
print now
type(now)

# Debug strf time
struct_now = time.localtime(now)
print struct_now
type(struct_now)

# Print nicely formatted date
print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)

# Get miliseconds
mlsec = repr(now).split('.')[1][:3]
print mlsec

# Get your required timestamp string
timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)
print timestamp

For clarification purposes, I also paste my Python 2.7.12 result here:

>>> import time
>>> # get current timestamp
... now = time.time()
>>> # debug now
... now
1484578293.519106
>>> print now
1484578293.52
>>> type(now)
<type 'float'>
>>> # debug strf time
... struct_now = time.localtime(now)
>>> print struct_now
time.struct_time(tm_year=2017, tm_mon=1, tm_mday=16, tm_hour=16, tm_min=51, tm_sec=33, tm_wday=0, tm_yday=16, tm_isdst=0)
>>> type(struct_now)
<type 'time.struct_time'>
>>> # print nicely formatted date
... print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)
2017-01-16 16:51:33 EET
>>> # get miliseconds
... mlsec = repr(now).split('.')[1][:3]
>>> print mlsec
519
>>> # get your required timestamp string
... timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)
>>> print timestamp
2017-01-16 16:51:33.519 EET
>>>

回答 3

这应该做的工作

import datetime
datetime.datetime.now().strftime("%H:%M:%S.%f")

它将打印

HH:MM:SS.microseconds 像这样 14:38:19.425961

This should do the work

import datetime
datetime.datetime.now().strftime("%H:%M:%S.%f")

It will print

HH:MM:SS.microseconds like this e.g 14:38:19.425961


回答 4

您还可以time使用其time()功能从模块获得微秒精度。
time.time()返回自纪元以来的时间(以秒为单位)。其小数部分是以微秒为单位的时间,这是您想要的。)

>>> from time import time
>>> time()
... 1310554308.287459   # the fractional part is what you want.


# comparision with strftime -
>>> from datetime import datetime
>>> from time import time
>>> datetime.now().strftime("%f"), time()
... ('287389', 1310554310.287459)

You can also get microsecond precision from the time module using its time() function.
(time.time() returns the time in seconds since epoch. Its fractional part is the time in microseconds, which is what you want.)

>>> from time import time
>>> time()
... 1310554308.287459   # the fractional part is what you want.


# comparision with strftime -
>>> from datetime import datetime
>>> from time import time
>>> datetime.now().strftime("%f"), time()
... ('287389', 1310554310.287459)

回答 5

如果微秒的“%f”不起作用,请使用以下方法:

import datetime

def getTimeStamp():
    dt = datetime.datetime.now()
    return dt.strftime("%Y%j%H%M%S") + str(dt.microsecond)

When the “%f” for micro seconds isn’t working, please use the following method:

import datetime

def getTimeStamp():
    dt = datetime.datetime.now()
    return dt.strftime("%Y%j%H%M%S") + str(dt.microsecond)

回答 6

如果要提高速度,请尝试以下操作:

def _timestamp(prec=0):
    t = time.time()
    s = time.strftime("%H:%M:%S", time.localtime(t))
    if prec > 0:
        s += ("%.9f" % (t % 1,))[1:2+prec]
    return s

prec精度在哪里-您想要多少个小数位。请注意,该函数与小数部分中的前导零没有问题,就像此处介绍的一些其他解决方案一样。

If you want speed, try this:

def _timestamp(prec=0):
    t = time.time()
    s = time.strftime("%H:%M:%S", time.localtime(t))
    if prec > 0:
        s += ("%.9f" % (t % 1,))[1:2+prec]
    return s

Where prec is precision — how many decimal places you want. Please note that the function does not have issues with leading zeros in fractional part like some other solutions presented here.


回答 7

如果需要整数,请尝试以下代码:

import datetime
print(datetime.datetime.now().strftime("%s%f")[:13])

输出:

1545474382803

If you want an integer, try this code:

import datetime
print(datetime.datetime.now().strftime("%s%f")[:13])

Output:

1545474382803

T和Z在时间戳中到底意味着什么?

问题:T和Z在时间戳中到底意味着什么?

我有这个时间戳值由Web服务返回 "2014-09-12T19:34:29Z"

我知道这意味着时区,但是那到底是什么意思呢?

而且我正在尝试模拟此Web服务,因此有没有办法strftime在python中使用生成此时间戳的方法?

很抱歉,如果这很明显,但Google的帮助不是很大,strftime()参考页面也没有。

我目前正在使用这个:

x.strftime("%Y-%m-%dT%H:%M:%S%Z")
'2015-03-26T10:58:51'

I have this timestamp value being return by a web service "2014-09-12T19:34:29Z"

I know that it means timezone, but what exactly does it mean?

And I am trying to mock this web service, so is there a way to generate this timestamp using strftime in python?

Sorry if this is painfully obvious, but Google was not very helpful and neither was the strftime() reference page.

I am currently using this :

x.strftime("%Y-%m-%dT%H:%M:%S%Z")
'2015-03-26T10:58:51'

回答 0

T并没有真正纳入什么。这仅仅是分隔ISO 8601相结合的日期时间格式要求。您可以将其阅读为Time的缩写。

Z代表的时区,因为它是由0从偏移协调世界时(UTC)

这两个字符都是格式上的静态字母,这就是为什么该datetime.strftime()方法未记录它们的原因。您可以使用QM或,Monty Python而该方法也可以将它们返回不变;该方法仅查找以开头的模式,%将其替换为来自datetime对象的信息。

The T doesn’t really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.


如何在熊猫中更改日期时间格式

问题:如何在熊猫中更改日期时间格式

我的数据框有一个DOB列(示例格式1/1/2016),默认情况下该列会转换为dtype’object’熊猫:DOB object

使用将日期转换为日期格式df['DOB'] = pd.to_datetime(df['DOB']),日期将转换为:2016-01-26,日期dtype为:DOB datetime64[ns]

现在,我想将此日期格式转换为01/26/2016任何其他通用日期格式或。我该怎么做?

无论我尝试哪种方法,它始终以2016-01-26格式显示日期。

My dataframe has a DOB column (example format 1/1/2016) which by default gets converted to pandas dtype ‘object’: DOB object

Converting this to date format with df['DOB'] = pd.to_datetime(df['DOB']), the date gets converted to: 2016-01-26 and its dtype is: DOB datetime64[ns].

Now I want to convert this date format to 01/26/2016 or in any other general date formats. How do I do it?

Whatever the method I try, it always shows the date in 2016-01-26 format.


回答 0

dt.strftime如果需要转换datetime为其他格式,可以使用(但请注意,dtype列的则为objectstring)):

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '26/1/2016'}})
print (df)
         DOB
0  26/1/2016 
1  26/1/2016

df['DOB'] = pd.to_datetime(df.DOB)
print (df)
         DOB
0 2016-01-26
1 2016-01-26

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print (df)
         DOB        DOB1
0 2016-01-26  01/26/2016
1 2016-01-26  01/26/2016

You can use dt.strftime if you need to convert datetime to other formats (but note that then dtype of column will be object (string)):

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '26/1/2016'}})
print (df)
         DOB
0  26/1/2016 
1  26/1/2016

df['DOB'] = pd.to_datetime(df.DOB)
print (df)
         DOB
0 2016-01-26
1 2016-01-26

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print (df)
         DOB        DOB1
0 2016-01-26  01/26/2016
1 2016-01-26  01/26/2016

回答 1

更改格式但不更改类型:

df['date'] = pd.to_datetime(df["date"].dt.strftime('%Y-%m'))

Changing the format but not changing the type:

df['date'] = pd.to_datetime(df["date"].dt.strftime('%Y-%m'))

回答 2

下面的代码对我有用,而不是上一个-试试看!

df['DOB']=pd.to_datetime(df['DOB'].astype(str), format='%m/%d/%Y')

The below code worked for me instead of the previous one – try it out !

df['DOB']=pd.to_datetime(df['DOB'].astype(str), format='%m/%d/%Y')

回答 3

与第一个答案相比,我建议先使用dt.strftime(),然后再使用pd.to_datetime()。这样,它将仍然导致datetime数据类型。

例如,

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016 ', 1: '26/1/2016 '})
print(df.dtypes)

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print(df.dtypes)

df['DOB1'] = pd.to_datetime(df['DOB1'])
print(df.dtypes)

Compared to the first answer, I will recommend to use dt.strftime() first, then pd.to_datetime(). In this way, it will still result in the datetime data type.

For example,

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016 ', 1: '26/1/2016 '})
print(df.dtypes)

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print(df.dtypes)

df['DOB1'] = pd.to_datetime(df['DOB1'])
print(df.dtypes)

回答 4

两者之间有区别

  • 数据帧单元的内容(二进制值)和
  • 它对我们(人类)的演示(展示)。

所以问题是:如何在不更改数据/数据类型本身的情况下达到我的数据的适当表示

答案是:

  • 如果您使用Jupyter笔记本显示数据,或者
  • 如果您想以HTML文件的形式进行演示(即使准备了许多多余的属性idclass属性来进行进一步的 CSS样式设置,则可以使用也可以不使用它们),

使用样式样式不会更改数据框列的数据/数据类型。

现在,我向您展示如何在Jupyter笔记本中找到它-有关HTML文件形式的演示文稿,请参阅问题末尾的注释。

我将假设您的列DOB 已经具有该类型datetime64(您已表明知道如何访问它)。我准备了一个简单的数据框(只有一列),向您展示了一些基本样式:

  • 没有样式:

       df
          DOB
0  2019-07-03
1  2019-08-03
2  2019-09-03
3  2019-10-03
  • 样式为mm/dd/yyyy

       df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})
          DOB
0  07/03/2019
1  08/03/2019
2  09/03/2019
3  10/03/2019
  • 样式为dd-mm-yyyy

       df.style.format({"DOB": lambda t: t.strftime("%d-%m-%Y")}) 
          DOB
0  03-07-2019
1  03-08-2019
2  03-09-2019
3  03-10-2019

小心!
返回的对象不是数据框-它是类的对象Styler,因此请勿将其分配回df

不要这样做:

df = df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})    # Don´t do this!

(每个数据框都可以通过其.style属性访问其Styler对象,我们更改了该df.style对象,而不是数据框本身。)


问题和解答:

  • 问: 为什么在Jupyter笔记本单元格中用作最后一条命令的Styler对象(或返回它的表达式)显示您的(样式化)表,而不显示Styler对象本身?

  • 答:因为每个Styler对象都有一个回调方法._repr_html_(),该方法返回用于呈现数据框的HTML代码(作为漂亮的HTML表)。

    Jupyter Notebook IDE 自动调用此方法以呈现具有此方法的对象。


注意:

您不需要Jupyter笔记本进行样式设置(即,在不更改数据/数据类型的情况下很好地输出数据框)。

render()如果您想使用HTML代码获取字符串(例如,用于将格式化的数据帧发布到Web上,或仅以HTML格式显示表格),则Styler对象也具有一种方法:

df_styler = df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})
HTML_string = df_styler.render()

There is a difference between

  • the content of a dataframe cell (a binary value) and
  • its presentation (displaying it) for us, humans.

So the question is: How to reach the appropriate presentation of my datas without changing the data / data types themselves?

Here is the answer:

  • If you use the Jupyter notebook for displaying your dataframe, or
  • if you want to reach a presentation in the form of an HTML file (even with many prepared superfluous id and class attributes for further CSS styling — you may or you may not use them),

use styling. Styling don’t change data / data types of columns of your dataframe.

Now I show you how to reach it in the Jupyter notebook — for a presentation in the form of HTML file see the note near the end of the question.

I will suppose that your column DOB already has the type datetime64 (you shown that you know how to reach it). I prepared a simple dataframe (with only one column) to show you some basic styling:

  • Not styled:

       df
    
          DOB
0  2019-07-03
1  2019-08-03
2  2019-09-03
3  2019-10-03
  • Styling it as mm/dd/yyyy:

       df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})
    
          DOB
0  07/03/2019
1  08/03/2019
2  09/03/2019
3  10/03/2019
  • Styling it as dd-mm-yyyy:

       df.style.format({"DOB": lambda t: t.strftime("%d-%m-%Y")}) 
    
          DOB
0  03-07-2019
1  03-08-2019
2  03-09-2019
3  03-10-2019

Be careful!
The returning object is NOT a dataframe — it is an object of the class Styler, so don’t assign it back to df:

Don´t do this:

df = df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})    # Don´t do this!

(Every dataframe has its Styler object accessible by its .style property, and we changed this df.style object, not the dataframe itself.)


Questions and Answers:

  • Q: Why your Styler object (or an expression returning it) used as the last command in a Jupyter notebook cell displays your (styled) table, and not the Styler object itself?

  • A: Because every Styler object has a callback method ._repr_html_() which returns an HTML code for rendering your dataframe (as a nice HTML table).

    Jupyter Notebook IDE calls this method automatically to render objects which have it.


Note:

You don’t need the Jupyter notebook for styling (i.e. for nice outputting a dataframe without changing its data / data types).

A Styler object has a method render(), too, if you want to obtain a string with the HTML code (e.g. for publishing your formatted dataframe to the Web, or simply present your table in the HTML format):

df_styler = df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})
HTML_string = df_styler.render()

回答 5

下面的代码更改为“ datetime”类型,并以给定的格式字符串格式化。效果很好!

df['DOB']=pd.to_datetime(df['DOB'].dt.strftime('%m/%d/%Y'))

Below code changes to ‘datetime’ type and also formats in the given format string. Works well!

df['DOB']=pd.to_datetime(df['DOB'].dt.strftime('%m/%d/%Y'))

回答 6

您可以尝试将日期格式转换为DD-MM-YYYY:

df['DOB'] = pd.to_datetime(df['DOB'], dayfirst = True)

You can try this it’ll convert the date format to DD-MM-YYYY:

df['DOB'] = pd.to_datetime(df['DOB'], dayfirst = True)

使用strftime将python datetime转换为纪元

问题:使用strftime将python datetime转换为纪元

我在UTC有一个时间,我想要从纪元开始经过的秒数。

我正在使用strftime将其转换为秒数。以2012年4月1日为例。

>>>datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'

从纪元开始的UTC时间为2012年4月1日,但以上返回1333234800,相差1小时。

因此,看来strftime正在考虑我的系统时间,并在某处应用了时区偏移。我以为日期时间纯粹是天真的?

我该如何解决?如果可能,除非标准,否则避免导入其他库。(我有可移植性问题)。

I have a time in UTC from which I want the number of seconds since epoch.

I am using strftime to convert it to the number of seconds. Taking 1st April 2012 as an example.

>>>datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'

1st of April 2012 UTC from epoch is 1333238400 but this above returns 1333234800 which is different by 1 hour.

So it looks like that strftime is taking my system time into account and applies a timezone shift somewhere. I thought datetime was purely naive?

How can I get around that? If possible avoiding to import other libraries unless standard. (I have portability concerns).


回答 0

如果要将python日期时间转换为自纪元以来的秒数,则可以明确地执行以下操作:

>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0

在Python 3.3+中,您可以timestamp()改用:

>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0

为什么不应该使用 datetime.strftime('%s')

Python实际上并不支持%s作为strftime的参数(如果您不在http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior中查看,则不在列表中),唯一之所以起作用,是因为Python会将信息传递到使用本地时区的系统的strftime中。

>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'

If you want to convert a python datetime to seconds since epoch you could do it explicitly:

>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0

In Python 3.3+ you can use timestamp() instead:

>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0

Why you should not use datetime.strftime('%s')

Python doesn’t actually support %s as an argument to strftime (if you check at http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior it’s not in the list), the only reason it’s working is because Python is passing the information to your system’s strftime, which uses your local timezone.

>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'

回答 1

我在时区等方面遇到了严重问题。Python处理所有事情的方式(对我而言)非常令人困惑。事情似乎使用日历模块(参见链接被精细工作1234)。

>>> import datetime
>>> import calendar
>>> aprilFirst=datetime.datetime(2012, 04, 01, 0, 0)
>>> calendar.timegm(aprilFirst.timetuple())
1333238400

I had serious issues with Timezones and such. The way Python handles all that happen to be pretty confusing (to me). Things seem to be working fine using the calendar module (see links 1, 2, 3 and 4).

>>> import datetime
>>> import calendar
>>> aprilFirst=datetime.datetime(2012, 04, 01, 0, 0)
>>> calendar.timegm(aprilFirst.timetuple())
1333238400

回答 2

import time
from datetime import datetime
now = datetime.now()

time.mktime(now.timetuple())
import time
from datetime import datetime
now = datetime.now()

time.mktime(now.timetuple())

回答 3

import time
from datetime import datetime
now = datetime.now()

# same as above except keeps microseconds
time.mktime(now.timetuple()) + now.microsecond * 1e-6

(对不起,它不会让我对现有答案发表评论)

import time
from datetime import datetime
now = datetime.now()

# same as above except keeps microseconds
time.mktime(now.timetuple()) + now.microsecond * 1e-6

(Sorry, it wouldn’t let me comment on existing answer)


回答 4

如果您只需要使用unix / epoch时间的时间戳,则此行可以工作:

created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L

并且仅取决于datetime python2和python3中的作品

if you just need a timestamp in unix /epoch time, this one line works:

created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L

and depends only on datetime works in python2 and python3


回答 5

这适用于Python 2和3:

>>> import time
>>> import calendar
>>> calendar.timegm(time.gmtime())
1504917998

仅遵循官方文档… https://docs.python.org/2/library/time.html#module-time

This works in Python 2 and 3:

>>> import time
>>> import calendar
>>> calendar.timegm(time.gmtime())
1504917998

Just following the official docs… https://docs.python.org/2/library/time.html#module-time


回答 6

对于明确的时区独立解决方案,请使用pytz库。

import datetime
import pytz

pytz.utc.localize(datetime.datetime(2012,4,1,0,0), is_dst=False).timestamp()

输出(浮动):1333238400.0

For an explicit timezone-independent solution, use the pytz library.

import datetime
import pytz

pytz.utc.localize(datetime.datetime(2012,4,1,0,0), is_dst=False).timestamp()

Output (float): 1333238400.0


回答 7

在Python 3.7中

以date.isoformat()和datetime.isoformat()发出的格式之一返回与date_string对应的datetime。具体来说,此函数支持格式为YYYY-MM-DD [* HH [:MM [:SS [.fff [fff]]]] [+ HH:MM [:SS [.ffffff]]]]的字符串,其中*可以匹配任何单个字符。

https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat

In Python 3.7

Return a datetime corresponding to a date_string in one of the formats emitted by date.isoformat() and datetime.isoformat(). Specifically, this function supports strings in the format(s) YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]], where * can match any single character.

https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat


Python strftime-日期前无0?

问题:Python strftime-日期前无0?

使用Python时strftime,有一种方法可以删除日期的第一个0(如果它在10之前)。所以011?找不到%东西吗?

谢谢!

When using Python strftime, is there a way to remove the first 0 of the date if it’s before the 10th, ie. so 01 is 1? Can’t find a %thingy for that?

Thanks!


回答 0

实际上,我遇到了同样的问题,并且我意识到,如果在%和字母之间添加连字符,则可以删除前导零。

例如%Y/%-m/%-d

这仅适用于Unix(Linux,OS X),而不适用于Windows(包括Cygwin)。在Windows上,您可以使用#,例如%Y/%#m/%#d

Actually I had the same problem and I realized that, if you add a hyphen between the % and the letter, you can remove the leading zero.

For example %Y/%-m/%-d.

This only works on Unix (Linux, OS X), not Windows (including Cygwin). On Windows, you would use #, e.g. %Y/%#m/%#d.


回答 1

format从python2.6开始,随着方法的出现,我们可以做这种事情:

>>> import datetime
>>> '{dt.year}/{dt.month}/{dt.day}'.format(dt = datetime.datetime.now())
'2013/4/19'

尽管可能超出原始问题的范围,但是对于更有趣的格式,您可以执行以下操作:

>>> '{dt:%A} {dt:%B} {dt.day}, {dt.year}'.format(dt=datetime.datetime.now())
'Wednesday December 3, 2014'

从python3.6开始,这可以表示为嵌入式格式的字符串

Python 3.6.0a2 (v3.6.0a2:378893423552, Jun 13 2016, 14:44:21) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dt = datetime.datetime.now()
>>> f'{dt:%A} {dt:%B} {dt.day}, {dt.year}'
'Monday August 29, 2016'

We can do this sort of thing with the advent of the format method since python2.6:

>>> import datetime
>>> '{dt.year}/{dt.month}/{dt.day}'.format(dt = datetime.datetime.now())
'2013/4/19'

Though perhaps beyond the scope of the original question, for more interesting formats, you can do stuff like:

>>> '{dt:%A} {dt:%B} {dt.day}, {dt.year}'.format(dt=datetime.datetime.now())
'Wednesday December 3, 2014'

And as of python3.6, this can be expressed as an inline formatted string:

Python 3.6.0a2 (v3.6.0a2:378893423552, Jun 13 2016, 14:44:21) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dt = datetime.datetime.now()
>>> f'{dt:%A} {dt:%B} {dt.day}, {dt.year}'
'Monday August 29, 2016'

回答 2

%根据http://docs.python.org/library/time.html的介绍,某些平台可能支持字母之间的宽度和精度规范(例如月份中的“ d”),但这绝对是不可移植的解决方案(例如,在我的Mac上不起作用;-)。也许您可以在之后使用字符串替换(或RE,对于真正讨厌的格式)strftime进行补救?例如:

>>> y
(2009, 5, 7, 17, 17, 17, 3, 127, 1)
>>> time.strftime('%Y %m %d', y)
'2009 05 07'
>>> time.strftime('%Y %m %d', y).replace(' 0', ' ')
'2009 5 7'

Some platforms may support width and precision specification between % and the letter (such as ‘d’ for day of month), according to http://docs.python.org/library/time.html — but it’s definitely a non-portable solution (e.g. doesn’t work on my Mac;-). Maybe you can use a string replace (or RE, for really nasty format) after the strftime to remedy that? e.g.:

>>> y
(2009, 5, 7, 17, 17, 17, 3, 127, 1)
>>> time.strftime('%Y %m %d', y)
'2009 05 07'
>>> time.strftime('%Y %m %d', y).replace(' 0', ' ')
'2009 5 7'

回答 3

strftime()GNU C库支持的修饰符的文档。(就像之前说过的那样,它可能不是便携式的。)您可能感兴趣的是:

  • %e而不是%d将月份中的前导零替换为空格

它适用于我的Python(在Linux上)。我不知道它是否对您有用。

Here is the documentation of the modifiers supported by strftime() in the GNU C library. (Like people said before, it might not be portable.) Of interest to you might be:

  • %e instead of %d will replace leading zero in day of month with a space

It works on my Python (on Linux). I don’t know if it will work on yours.


回答 4

>>> import datetime
>>> d = datetime.datetime.now()
>>> d.strftime('X%d/X%m/%Y').replace('X0','X').replace('X','')
'5/5/2011'
>>> import datetime
>>> d = datetime.datetime.now()
>>> d.strftime('X%d/X%m/%Y').replace('X0','X').replace('X','')
'5/5/2011'

回答 5

在Windows上,添加一个’#’,例如’%#m /%#d /%Y%#I:%M:%S%p’

供参考:https : //msdn.microsoft.com/en-us/library/fe06s4ak.aspx

On Windows, add a ‘#’, as in ‘%#m/%#d/%Y %#I:%M:%S %p’

For reference: https://msdn.microsoft.com/en-us/library/fe06s4ak.aspx


回答 6

晚会很晚,但是%-d对我有帮助。

datetime.now().strftime('%B %-d, %Y')产生类似“ 2014年11月5日”的内容

欢呼:)

quite late to the party but %-d works on my end.

datetime.now().strftime('%B %-d, %Y') produces something like “November 5, 2014”

cheers :)


回答 7

我发现Django模板日期格式过滤器非常简单快捷。它去除了前导零。如果您不介意导入Django模块,请签出。

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date

from django.template.defaultfilters import date as django_date_filter
print django_date_filter(mydate, 'P, D M j, Y')    

I find the Django template date formatting filter to be quick and easy. It strips out leading zeros. If you don’t mind importing the Django module, check it out.

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date

from django.template.defaultfilters import date as django_date_filter
print django_date_filter(mydate, 'P, D M j, Y')    

回答 8

看一下-波纹管:

>>> from datetime import datetime
>>> datetime.now().strftime('%d-%b-%Y')
>>> '08-Oct-2011'
>>> datetime.now().strftime('%-d-%b-%Y')
>>> '8-Oct-2011'
>>> today = datetime.date.today()
>>> today.strftime('%d-%b-%Y')
>>> print(today)

Take a look at - bellow:

>>> from datetime import datetime
>>> datetime.now().strftime('%d-%b-%Y')
>>> '08-Oct-2011'
>>> datetime.now().strftime('%-d-%b-%Y')
>>> '8-Oct-2011'
>>> today = datetime.date.today()
>>> today.strftime('%d-%b-%Y')
>>> print(today)

回答 9

只需这样使用replace

(datetime.date.now()).strftime("%Y/%m/%d").replace("/0", "/")

它会输出:

'2017/7/21'

simply use replace like this:

(datetime.date.now()).strftime("%Y/%m/%d").replace("/0", "/")

it will output:

'2017/7/21'

回答 10

因为%d您可以使用转换为整数,int()否则它将自动删除前导0并变为整数。然后,您可以使用将其转换回字符串str()

For %d you can convert to integer using int() then it’ll automatically remove leading 0 and becomes integer. You can then convert back to string using str().


回答 11

例如,即使在同一OS的不同版本之间使用“%-d”也不是可移植的。更好的解决方案是分别提取日期成分,然后在日期特定的格式运算符和每个成分的日期属性访问之间进行选择。

e = datetime.date(2014, 1, 6)
"{date:%A} {date.day} {date:%B}{date.year}".format(date=e)

using, for example, “%-d” is not portable even between different versions of the same OS. A better solution would be to extract the date components individually, and choose between date specific formatting operators and date attribute access for each component.

e = datetime.date(2014, 1, 6)
"{date:%A} {date.day} {date:%B}{date.year}".format(date=e)

回答 12

因为Python实际上只是strftime(3)在您的平台上调用C语言函数,所以可能是有些格式字符可用于控制前导零;尝试man strftime看看。但是,当然,结果不会是可移植的,因为Python手册会提醒您。:-)

我会尝试使用一种新样式的datetime对象,该对象具有诸如t.yeart.month和的属性t.day,并通过%运算符的正常高效能格式来设置这些对象,该格式确实支持对前导零的控制。有关详细信息,请参见http://docs.python.org/library/datetime.html。更好的是,"".format()如果您的Python拥有运算符,并且更现代,请使用运算符。它也有许多数字格式选项。请参阅:http : //docs.python.org/library/string.html#string-formatting

Because Python really just calls the C language strftime(3) function on your platform, it might be that there are format characters you could use to control the leading zero; try man strftime and take a look. But, of course, the result will not be portable, as the Python manual will remind you. :-)

I would try using a new-style datetime object instead, which has attributes like t.year and t.month and t.day, and put those through the normal, high-powered formatting of the % operator, which does support control of leading zeros. See http://docs.python.org/library/datetime.html for details. Better yet, use the "".format() operator if your Python has it and be even more modern; it has lots of format options for numbers as well. See: http://docs.python.org/library/string.html#string-formatting.


回答 13

基于Alex的方法,这将适用于字符串开头和空格后的情况:

re.sub('^0|(?<= )0', '', "01 January 2000 08:00am")

我喜欢它比.format或%-d好,因为它是跨平台的,可以让我继续使用strftime(获取“ 11月”和“星期一”之类的信息)。

Based on Alex’s method, this will work for both the start-of-string and after-spaces cases:

re.sub('^0|(?<= )0', '', "01 January 2000 08:00am")

I like this better than .format or %-d because this is cross-platform and allows me to keep using strftime (to get things like “November” and “Monday”).


回答 14

老问题了,但是%l(小写L)在strftime中对我有用:但是,这可能不适用于每个人,因为我发现的Python文档中未列出

Old question, but %l (lower-case L) worked for me in strftime: this may not work for everyone, though, as it’s not listed in the Python documentation I found


回答 15

import datetime
now = datetime.datetime.now()
print now.strftime("%b %_d")
import datetime
now = datetime.datetime.now()
print now.strftime("%b %_d")

将Unix时间戳字符串转换为可读日期

问题:将Unix时间戳字符串转换为可读日期

我有一个表示Python中的unix时间戳的字符串(即“ 1284101485”),我想将其转换为可读的日期。使用时time.strftime,我得到TypeError

>>>import time
>>>print time.strftime("%B %d %Y", "1284101485")

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not str

I have a string representing a unix timestamp (i.e. “1284101485”) in Python, and I’d like to convert it to a readable date. When I use time.strftime, I get a TypeError:

>>>import time
>>>print time.strftime("%B %d %Y", "1284101485")

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not str

回答 0

使用datetime模块:

from datetime import datetime
ts = int("1284101485")

# if you encounter a "year is out of range" error the timestamp
# may be in milliseconds, try `ts /= 1000` in that case
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

Use datetime module:

from datetime import datetime
ts = int("1284101485")

# if you encounter a "year is out of range" error the timestamp
# may be in milliseconds, try `ts /= 1000` in that case
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

回答 1

>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)

取自http://seehuhn.de/pages/pdate

>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)

Taken from http://seehuhn.de/pages/pdate


回答 2

投票最多的答案建议使用fromtimestamp,因为它使用本地时区,因此容易出错。为了避免出现问题,更好的方法是使用UTC:

datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')

其中posix_time是要转换的Posix纪元时间

The most voted answer suggests using fromtimestamp which is error prone since it uses the local timezone. To avoid issues a better approach is to use UTC:

datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')

Where posix_time is the Posix epoch time you want to convert


回答 3

>>> import time
>>> time.ctime(int("1284101485"))
'Fri Sep 10 16:51:25 2010'
>>> time.strftime("%D %H:%M", time.localtime(int("1284101485")))
'09/10/10 16:51'
>>> import time
>>> time.ctime(int("1284101485"))
'Fri Sep 10 16:51:25 2010'
>>> time.strftime("%D %H:%M", time.localtime(int("1284101485")))
'09/10/10 16:51'

回答 4

有两个部分:

  1. 将Unix时间戳(“自纪元以来的秒数”)转换为本地时间
  2. 以所需格式显示当地时间。

即使本地时区过去有不同的utc偏移并且python无法访问tz数据库,获取本地时间有效的一种便携式方法是使用pytz时区:

#!/usr/bin/env python
from datetime import datetime
import tzlocal  # $ pip install tzlocal

unix_timestamp = float("1284101485")
local_timezone = tzlocal.get_localzone() # get pytz timezone
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)

要显示它,您可以使用系统支持的任何时间格式,例如:

print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
print(local_time.strftime("%B %d %Y"))  # print date in your format

如果您不需要当地时间,请改为获取可读的UTC时间:

utc_time = datetime.utcfromtimestamp(unix_timestamp)
print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)"))

如果您不关心可能影响返回日期的时区问题,或者python是否有权访问系统上的tz数据库:

local_time = datetime.fromtimestamp(unix_timestamp)
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f"))

在Python 3上,您可以仅使用stdlib获得时区感知日期时间(如果python无法访问系统上的tz数据库,例如Windows上的UTC偏移量可能是错误的):

#!/usr/bin/env python3
from datetime import datetime, timezone

utc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc)
local_time = utc_time.astimezone()
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))

time模块中的函数是对应C API的薄包装,因此它们可能比对应datetime方法的可移植性差,否则您也可以使用它们:

#!/usr/bin/env python
import time

unix_timestamp  = int("1284101485")
utc_time = time.gmtime(unix_timestamp)
local_time = time.localtime(unix_timestamp)
print(time.strftime("%Y-%m-%d %H:%M:%S", local_time)) 
print(time.strftime("%Y-%m-%d %H:%M:%S+00:00 (UTC)", utc_time))  

There are two parts:

  1. Convert the unix timestamp (“seconds since epoch”) to the local time
  2. Display the local time in the desired format.

A portable way to get the local time that works even if the local time zone had a different utc offset in the past and python has no access to the tz database is to use a pytz timezone:

#!/usr/bin/env python
from datetime import datetime
import tzlocal  # $ pip install tzlocal

unix_timestamp = float("1284101485")
local_timezone = tzlocal.get_localzone() # get pytz timezone
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)

To display it, you could use any time format that is supported by your system e.g.:

print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
print(local_time.strftime("%B %d %Y"))  # print date in your format

If you do not need a local time, to get a readable UTC time instead:

utc_time = datetime.utcfromtimestamp(unix_timestamp)
print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)"))

If you don’t care about the timezone issues that might affect what date is returned or if python has access to the tz database on your system:

local_time = datetime.fromtimestamp(unix_timestamp)
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f"))

On Python 3, you could get a timezone-aware datetime using only stdlib (the UTC offset may be wrong if python has no access to the tz database on your system e.g., on Windows):

#!/usr/bin/env python3
from datetime import datetime, timezone

utc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc)
local_time = utc_time.astimezone()
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))

Functions from the time module are thin wrappers around the corresponding C API and therefore they may be less portable than the corresponding datetime methods otherwise you could use them too:

#!/usr/bin/env python
import time

unix_timestamp  = int("1284101485")
utc_time = time.gmtime(unix_timestamp)
local_time = time.localtime(unix_timestamp)
print(time.strftime("%Y-%m-%d %H:%M:%S", local_time)) 
print(time.strftime("%Y-%m-%d %H:%M:%S+00:00 (UTC)", utc_time))  

回答 5

为了使UNIX时间戳易于理解,我以前在脚本中使用过它:

import os, datetime

datetime.datetime.fromtimestamp(float(os.path.getmtime("FILE"))).strftime("%B %d, %Y")

输出:

‘2012年12月26日’

For a human readable timestamp from a UNIX timestamp, I have used this in scripts before:

import os, datetime

datetime.datetime.fromtimestamp(float(os.path.getmtime("FILE"))).strftime("%B %d, %Y")

Output:

‘December 26, 2012’


回答 6

您可以像这样转换当前时间

t=datetime.fromtimestamp(time.time())
t.strftime('%Y-%m-%d')
'2012-03-07'

将字符串中的日期转换为其他格式。

import datetime,time

def createDateObject(str_date,strFormat="%Y-%m-%d"):    
    timeStamp = time.mktime(time.strptime(str_date,strFormat))
    return datetime.datetime.fromtimestamp(timeStamp)

def FormatDate(objectDate,strFormat="%Y-%m-%d"):
    return objectDate.strftime(strFormat)

Usage
=====
o=createDateObject('2013-03-03')
print FormatDate(o,'%d-%m-%Y')

Output 03-03-2013

You can convert the current time like this

t=datetime.fromtimestamp(time.time())
t.strftime('%Y-%m-%d')
'2012-03-07'

To convert a date in string to different formats.

import datetime,time

def createDateObject(str_date,strFormat="%Y-%m-%d"):    
    timeStamp = time.mktime(time.strptime(str_date,strFormat))
    return datetime.datetime.fromtimestamp(timeStamp)

def FormatDate(objectDate,strFormat="%Y-%m-%d"):
    return objectDate.strftime(strFormat)

Usage
=====
o=createDateObject('2013-03-03')
print FormatDate(o,'%d-%m-%Y')

Output 03-03-2013

回答 7

除了使用time / datetime包之外,pandas还可以用于解决相同的问题。这是我们可以使用pandas时间戳转换为可读日期的方法

时间戳可以有两种格式:

  1. 13位数字(毫秒)-要将毫秒转换日期,请使用:

    import pandas
    result_ms=pandas.to_datetime('1493530261000',unit='ms')
    str(result_ms)
    
    Output: '2017-04-30 05:31:01'
  2. 10位(秒)-要将转换为日期,请使用:

    import pandas
    result_s=pandas.to_datetime('1493530261',unit='s')
    str(result_s)
    
    Output: '2017-04-30 05:31:01'

Other than using time/datetime package, pandas can also be used to solve the same problem.Here is how we can use pandas to convert timestamp to readable date:

Timestamps can be in two formats:

  1. 13 digits(milliseconds) – To convert milliseconds to date, use:

    import pandas
    result_ms=pandas.to_datetime('1493530261000',unit='ms')
    str(result_ms)
    
    Output: '2017-04-30 05:31:01'
    
  2. 10 digits(seconds) – To convert seconds to date, use:

    import pandas
    result_s=pandas.to_datetime('1493530261',unit='s')
    str(result_s)
    
    Output: '2017-04-30 05:31:01'
    

回答 8

timestamp ="124542124"
value = datetime.datetime.fromtimestamp(timestamp)
exct_time = value.strftime('%d %B %Y %H:%M:%S')

您还可以从时间戳获取带有时间的可读日期,也可以更改日期格式。

timestamp ="124542124"
value = datetime.datetime.fromtimestamp(timestamp)
exct_time = value.strftime('%d %B %Y %H:%M:%S')

Get the readable date from timestamp with time also, also you can change the format of the date.


回答 9

在Python 3.6+中:

import datetime

timestamp = 1579117901
value = datetime.datetime.fromtimestamp(timestamp)
print(f"{value:%Y-%m-%d %H:%M:%S}")

输出:

2020-01-15 19:51:41

说明:

In Python 3.6+:

import datetime

timestamp = 1579117901
value = datetime.datetime.fromtimestamp(timestamp)
print(f"{value:%Y-%m-%d %H:%M:%S}")

Output:

2020-01-15 19:51:41

Explanation:


回答 10

import datetime
temp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')
print temp
import datetime
temp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')
print temp

回答 11

可以使用gmtime和format函数完成此操作的另一种方法;

from time import gmtime
print('{}-{}-{} {}:{}:{}'.format(*gmtime(1538654264.703337)))

输出: 2018-10-4 11:57:44

Another way that this can be done using gmtime and format function;

from time import gmtime
print('{}-{}-{} {}:{}:{}'.format(*gmtime(1538654264.703337)))

Output: 2018-10-4 11:57:44


回答 12

我刚刚成功使用过:

>>> type(tstamp)
pandas.tslib.Timestamp
>>> newDt = tstamp.date()
>>> type(newDt)
datetime.date

i just successfully used:

>>> type(tstamp)
pandas.tslib.Timestamp
>>> newDt = tstamp.date()
>>> type(newDt)
datetime.date

回答 13

快速又脏的一个衬里:

'-'.join(str(x) for x in list(tuple(datetime.datetime.now().timetuple())[:6]))

‘2013-5-5-1-9-43’

quick and dirty one liner:

'-'.join(str(x) for x in list(tuple(datetime.datetime.now().timetuple())[:6]))

‘2013-5-5-1-9-43’


回答 14

您可以使用easy_date使其变得容易:

import date_converter
my_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")

You can use easy_date to make it easy:

import date_converter
my_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")