Reputation: 768
I am working on a script were I must work with datetime objects in Python. At some point I have one of those objects and I need to get the day of the week (which is a number value) in a 3-letter format (i.e. Tue, Wed, etc.). Here is a brief sample of the code, in dateMatch.group() all I am doing is getting pieces of a string obtained via regex matching.
from datetime import datetime
day = dateMatch.group(2)
month = dateMatch.group(3)
year = dateMatch.group(4)
hour = dateMatch.group(5)
minute = dateMatch.group(6)
second = dateMatch.group(7)
tweetDate = datetime(int(year), months[month], int(day), int(hour), int(minute), int(second))
From that date time object I get a numerical day value (i.e. 18) and I need to convert it to (i.e. Tue).
Thanks!
Upvotes: 14
Views: 18294
Reputation: 751
Instead of hardcoding ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"], try:
import calendar
weekdays = [x for x in calendar.day_abbr] # in the current locale
Upvotes: 0
Reputation: 21
The doc I used: http://docs.python.org/2/library/datetime.html
First you need todays date:
today = date.today() # Which returns a date object
The weekday can be found from a date object by using:
weekday = today.timetuple()[6] # Getting the 6th item in the tuple returned by timetuple
This returns days since Monday (0 would be Monday), using this integer you can do the following:
print ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"][weekday] # Prints out the weekday in three chars
Combined you get:
from datetime import date
today = date.today() # Gets the date in format "yyyy-mm-ddd"
print today
weekday = today.timetuple()[6] # Gets the days from monday
print ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"][weekday] # Prints out the weekday in three chars
Upvotes: 0
Reputation: 65884
The strftime
method of a datetime
object uses the current locale to determine the conversion.
>>> from datetime import datetime
>>> t = datetime.now()
>>> t.strftime('%a')
'Tue'
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'fr_FR')
'fr_FR'
>>> t.strftime('%a')
'Mar'
If this is not acceptable (for example, if you're formatting a date for transmission over an Internet protocol, you may actually require the string Tue
regardless of the user's locale), then you need something like:
weekdays = 'Mon Tue Wed Thu Fri Sat Sun'.split()
return weekdays[datetime.now().weekday()]
Or you could explicitly request the "C" locale:
locale.setlocale(locale.LC_TIME, 'C')
return datetime.now().strftime('%a')
but setting the locale like this affects all formatting operations on all threads in your program, so it might not be such a good idea.
Upvotes: 7
Reputation: 62948
http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
date, datetime, and time objects all support a
strftime(format)
method, to create a string representing the time under the control of an explicit format string....
%a — Locale’s abbreviated weekday name.
>>> datetime.datetime.now().strftime('%a')
'Wed'
Upvotes: 23