简体   繁体   English

将日期字符串转换为星期几

[英]Convert Date String to Day of Week

I have date strings like this: 我有这样的日期字符串:

'January 11, 2010'

and I need a function that returns the day of the week, like 我需要一个返回星期几的函数,比如

'mon', or 'monday'

etc. I can't find this anywhere in the Python help. 我在Python帮助中的任何地方都找不到这个。 Anyone? 任何人? Thanks. 谢谢。

You might want to use strptime and strftime methods from datetime : 您可能希望使用datetime strptime and strftime方法:

>>> import datetime
>>> datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')
'Monday'

or for 'Mon' : 'Mon'

>>> datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%a')
'Mon'

use date.weekday() Return the day of the week as an integer, where Monday is 0 and Sunday is 6. use date.weekday()以星期为单位返回星期几,其中星期一为0,星期日为6。

http://docs.python.org/2/library/datetime.html#datetime.date.weekday http://docs.python.org/2/library/datetime.html#datetime.date.weekday

A third-party parser could be used, such as dateutil . 可以使用第三方解析器,例如dateutil

And code for your original question: 和原始问题的代码:

>>> from dateutil import parser
>>> parser.parse('January 11, 2010').strftime("%a")
'Mon'
>>> parser.parse('January 11, 2010').strftime("%A")
'Monday'

我认为最快的方法就像下面这样:

df[Date_Column].dt.weekday_name
>>> import time
>>> dateStr = 'January 11, 2010'
>>> timestamp = time.strptime(dateStr, '%B %d, %Y')
>>> timestamp
time.struct_time(tm_year=2010, tm_mon=1, tm_mday=11, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=11, tm_isdst=-1)
import time

time.strftime('%A')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM