By Oli


2009-01-21 18:00:29 8 Comments

Short and simple. I've got a huge list of date-times like this as strings:

Jun 1 2005  1:33PM
Aug 28 1999 12:00AM

I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.

Any help (even if it's just a kick in the right direction) would be appreciated.

Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.

22 comments

@Domi W 2019-04-10 11:56:34

You could also use facebook's duckling.

Try it out online here: https://duckling.wit.ai/

There is a python wrapper for the library: pip install duckling

It supports much more than only time parsing.

@SuperNova 2019-02-22 15:35:25

In Python >= 3.7.0,

to convert YYYY-MM-DD string to datetime object, datetime.fromisoformat could be used.

>>> from datetime import datetime

>>> date_string = "2012-12-12 10:10:10"
>>> print (datetime.fromisoformat(date_string))
>>> 2012-12-12 10:10:10

@Riz.Khan 2019-01-01 12:17:51

emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv")
emp.info()

it shows "Start Date Time" Column and "Last Login Time" both are "object = strings" in data-frame

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 8 columns):
First Name           933 non-null object
Gender               855 non-null object
Start Date           1000 non-null object

Last Login Time      1000 non-null object
Salary               1000 non-null int64
Bonus %              1000 non-null float64
Senior Management    933 non-null object
Team                 957 non-null object
dtypes: float64(1), int64(1), object(6)
memory usage: 62.6+ KB

By using parse_dates option in read_csv mention you can convert your string datetime into pandas datetime format.

emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv", parse_dates=["Start Date", "Last Login Time"])
emp.info()


<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 8 columns):
First Name           933 non-null object
Gender               855 non-null object
Start Date           1000 non-null datetime64[ns]
Last Login Time      1000 non-null datetime64[ns]
Salary               1000 non-null int64
Bonus %              1000 non-null float64
Senior Management    933 non-null object
Team                 957 non-null object
dtypes: datetime64[ns](2), float64(1), int64(1), object(4)
memory usage: 62.6+ KB

@user1767754 2018-01-02 00:04:19

I personally like the solution using the parser module, which is the second Answer to this question and is beautiful, as you don't have to construct any string literals to get it working. BUT, one downside is that it is 90% slower than the accepted answer with strptime.

from dateutil import parser
from datetime import datetime
import timeit

def dt():
    dt = parser.parse("Jun 1 2005  1:33PM")
def strptime():
    datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

print(timeit.timeit(stmt=dt, number=10**5))
print(timeit.timeit(stmt=strptime, number=10**5))
>10.70296801342902
>1.3627995655316933

As long as you are not doing this a million times over and over again, I still think the parser method is more convenient and will handle most of the time formats automatically.

@Toskan 2018-10-15 21:02:39

for unix / mysql format 2018-10-15 20:59:29

from datetime import datetime

datetime_object = datetime.strptime('2018-10-15 20:59:29', '%Y-%m-%d %H:%M:%S')

@smci 2017-12-18 21:12:03

See my answer.

In real-world data this is a real problem: multiple, mismatched, incomplete, inconsistent and multilanguage/region date formats, often mixed freely in one dataset. It's not ok for production code to fail, let alone go exception-happy like a fox.

We need to try...catch multiple datetime formats fmt1,fmt2,...,fmtn and suppress/handle the exceptions (from strptime()) for all those that mismatch (and in particular, avoid needing a yukky n-deep indented ladder of try..catch clauses). From my solution

def try_strptime(s, fmts=['%d-%b-%y','%m/%d/%Y']):
    for fmt in fmts:
        try:
            return datetime.strptime(s, fmt)
        except:
            continue

    return None # or reraise the ValueError if no format matched, if you prefer

@RoG 2018-10-02 12:28:51

The question said nothing about "multiple, mismatched, incomplete, inconsistent and multilanguage/region date formats" etc. This may be a real problem, but not relevant here.

@smci 2018-10-02 19:38:11

@RoG: It never said they weren't, and it implied they were: "huge list... database". In most every database/logfile I've worked on (even small-size), there were multiple date formats, timezone identifiers, MM-DD etc. In production it is unacceptable to write brittle code which hardcodes in formats and crashes with exception when it doesn't get the format it expected (even returning None or '' is more acceptable). Hence a need for multiple formats. Hence this does address the question asked, and I spent a bit of time figuring out the most Pythonic way to handle errors from multiple formats.

@RoG 2018-10-03 07:28:15

"huge list... database" simply implies that there are a lot of them, not that they are all different formats. It is totally acceptable to write code which reads a single format, if you know that there is a single format in the input. In this case it should crash if it is passed something that is not in the right format.

@Kanish Mathew 2018-08-16 04:17:16

It would do the helpful for converting string to datetime and also with time zone

def convert_string_to_time(date_string, timezone):
    from datetime import datetime
    import pytz
    date_time_obj = datetime.strptime(date_string[:26], '%Y-%m-%d %H:%M:%S.%f')
    date_time_obj_timezone = pytz.timezone(timezone).localize(date_time_obj)

    return date_time_obj_timezone

date = '2018-08-14 13:09:24.543953+00:00'
TIME_ZONE = 'UTC'
date_time_obj_timezone = convert_string_to_time(date, TIME_ZONE)

@Harry Moreno 2018-08-29 19:59:58

I needed a datetime string with timezone 👌

@Javed 2017-12-21 12:44:11

If you want only date format then you can manually convert it by passing your individual fields like:

>>> import datetime
>>> date = datetime.date(int('2017'),int('12'),int('21'))
>>> date
datetime.date(2017, 12, 21)
>>> type(date)
<type 'datetime.date'>

You can pass your split string values to convert it into date type like:

selected_month_rec = '2017-09-01'
date_formate = datetime.date(int(selected_month_rec.split('-')[0]),int(selected_month_rec.split('-')[1]),int(selected_month_rec.split('-')[2]))

You will get the resulting value in date format.

@Bill Bell 2017-02-28 17:37:39

arrow offers many useful functions for dates and times. This bit of code provides an answer to the question and shows that arrow is also capable of formatting dates easily and displaying information for other locales.

>>> import arrow
>>> dateStrings = [ 'Jun 1  2005 1:33PM', 'Aug 28 1999 12:00AM' ]
>>> for dateString in dateStrings:
...     dateString
...     arrow.get(dateString.replace('  ',' '), 'MMM D YYYY H:mmA').datetime
...     arrow.get(dateString.replace('  ',' '), 'MMM D YYYY H:mmA').format('ddd, Do MMM YYYY HH:mm')
...     arrow.get(dateString.replace('  ',' '), 'MMM D YYYY H:mmA').humanize(locale='de')
...
'Jun 1  2005 1:33PM'
datetime.datetime(2005, 6, 1, 13, 33, tzinfo=tzutc())
'Wed, 1st Jun 2005 13:33'
'vor 11 Jahren'
'Aug 28 1999 12:00AM'
datetime.datetime(1999, 8, 28, 0, 0, tzinfo=tzutc())
'Sat, 28th Aug 1999 00:00'
'vor 17 Jahren'

See http://arrow.readthedocs.io/en/latest/ for more.

@Rajiv Sharma 2016-06-24 04:07:27

The datetime Python module is good for getting date time and converting date time formats.

import datetime

new_date_format1 = datetime.datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')
new_date_format2 = datetime.datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p').strftime('%Y/%m/%d %I:%M%p')
print new_date_format1
print new_date_format2

Output:

2005-06-01 13:33:00
2005/06/01 01:33PM

@Mackraken 2016-02-04 13:43:07

Create a small utility function like:

def date(datestr="", format="%Y-%m-%d"):
    from datetime import datetime
    if not datestr:
        return datetime.today().date()
    return datetime.strptime(datestr, format).date()

This is versatile enough:

  • If you don't pass any arguments it will return today's date.
  • There's a date format as default that you can override.
  • You can easily modify it to return a datetime.

@shredding 2017-01-10 09:30:06

format is a reserved word in python and shouldn't be used as a variable name.

@Patrick Harrington 2009-01-21 18:08:52

datetime.strptime is the main routine for parsing strings into datetimes. It can handle all sorts of formats, with the format determined by a format string you give it:

from datetime import datetime

datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

The resulting datetime object is timezone-naive.

Links:

Notes:

  • strptime = "string parse time"
  • strftime = "string format time"
  • Pronounce it out loud today & you won't have to search for it again in 6 months.

@jononomo 2014-04-28 19:07:23

why does that return a date_object and not a datetime_object?

@jfs 2014-04-29 10:55:04

'%b', '%p' may fail in non-English locale.

@User 2014-04-30 01:56:29

What is the string doesn't have the time, just "April 25, 2014"

@Izkata 2014-11-11 20:02:07

@User You'll have to know ahead of time to exclude that part of the format string, but if you want a date instead of a datetime, going through datetime handles it nicely: datetime.strptime('Jun 1 2005', '%b %d %Y').date() == date(2005, 6, 1)

@gaoithe 2015-10-07 10:28:04

To parse default unix 'date' command output which has timezone in it e.g. "Sun Oct 4 07:48:48 UTC 2015" one can use datetime.strptime(currentDateStr, "%a %b %d %H:%M:%S %Z %Y").

@Mitch 2016-09-20 17:25:01

Note that this function was added sometime between python 2.4.3 and python 2.6

@Gagandeep Singh 2016-12-04 12:33:14

guessing strptime is always time consuming complex task for this I created one service for help. check out percepty.com/…

@Flimm 2016-12-08 10:28:38

If you know the string represents a datetime in UTC, you can get a timezone aware datetime object by adding this line in Python 3: from datetime import timezone; datetime_object = datetime_object.replace(tzinfo=timezone.utc)

@TheJKFever 2017-03-22 19:07:20

Any idea how to get a timezone aware datetime in python prior to 3?

@Martin Thoma 2017-12-07 13:56:30

I was looking for "%Y-%m-%d %H:%M:%S"

@Bitcoin Murderous Maniac 2018-04-18 22:56:45

I was looking for "%Y-%m-%d %H:%M:%S.%f".... Seems to be a bit more than 2018 up votes now too....

@Aminah Nuraini 2018-10-20 06:41:45

I got this error AttributeError: 'module' object has no attribute 'strptime'

@Max Strater 2018-11-12 21:02:05

@AminahNuraini I got around a similar issue by doing from datetime import datetime instead of just import datetime.

@Alexander 2015-12-20 03:03:25

Here are two solutions using Pandas to convert dates formatted as strings into datetime.date objects.

import pandas as pd

dates = ['2015-12-25', '2015-12-26']

# 1) Use a list comprehension.
>>> [d.date() for d in pd.to_datetime(dates)]
[datetime.date(2015, 12, 25), datetime.date(2015, 12, 26)]

# 2) Convert the dates to a DatetimeIndex and extract the python dates.
>>> pd.DatetimeIndex(dates).date.tolist()
[datetime.date(2015, 12, 25), datetime.date(2015, 12, 26)]

Timings

dates = pd.DatetimeIndex(start='2000-1-1', end='2010-1-1', freq='d').date.tolist()

>>> %timeit [d.date() for d in pd.to_datetime(dates)]
# 100 loops, best of 3: 3.11 ms per loop

>>> %timeit pd.DatetimeIndex(dates).date.tolist()
# 100 loops, best of 3: 6.85 ms per loop

And here is how to convert the OP's original date-time examples:

datetimes = ['Jun 1 2005  1:33PM', 'Aug 28 1999 12:00AM']

>>> pd.to_datetime(datetimes).to_pydatetime().tolist()
[datetime.datetime(2005, 6, 1, 13, 33), 
 datetime.datetime(1999, 8, 28, 0, 0)]

There are many options for converting from the strings to Pandas Timestamps using to_datetime, so check the docs if you need anything special.

Likewise, Timestamps have many properties and methods that can be accessed in addition to .date

@Rizwan Mumtaz 2014-12-10 13:00:49

Remember this and you didn't need to get confused in datetime conversion again.

String to datetime object = strptime

datetime object to other formats = strftime

Jun 1 2005 1:33PM

is equals to

%b %d %Y %I:%M%p

%b Month as locale’s abbreviated name(Jun)

%d Day of the month as a zero-padded decimal number(1)

%Y Year with century as a decimal number(2015)

%I Hour (12-hour clock) as a zero-padded decimal number(01)

%M Minute as a zero-padded decimal number(33)

%p Locale’s equivalent of either AM or PM(PM)

so you need strptime i-e converting string to

>>> dates = []
>>> dates.append('Jun 1 2005  1:33PM')
>>> dates.append('Aug 28 1999 12:00AM')
>>> from datetime import datetime
>>> for d in dates:
...     date = datetime.strptime(d, '%b %d %Y %I:%M%p')
...     print type(date)
...     print date
... 

Output

<type 'datetime.datetime'>
2005-06-01 13:33:00
<type 'datetime.datetime'>
1999-08-28 00:00:00

What if you have different format of dates you can use panda or dateutil.parse

>>> import dateutil
>>> dates = []
>>> dates.append('12 1 2017')
>>> dates.append('1 1 2017')
>>> dates.append('1 12 2017')
>>> dates.append('June 1 2017 1:30:00AM')
>>> [parser.parse(x) for x in dates]

OutPut

[datetime.datetime(2017, 12, 1, 0, 0), datetime.datetime(2017, 1, 1, 0, 0), datetime.datetime(2017, 1, 12, 0, 0), datetime.datetime(2017, 6, 1, 1, 30)]

@optimist 2017-06-09 05:42:48

%S for Seconds as decimal

@bfontaine 2018-05-08 09:44:38

Won’t %b break if you parse an English date on a machine that doesn’t have an English locale?

@Steve Peak 2014-03-02 14:22:44

I have put together a project that can convert some really neat expressions. Check out timestring.

Here are some examples below:

pip install timestring
>>> import timestring
>>> timestring.Date('monday, aug 15th 2015 at 8:40 pm')
<timestring.Date 2015-08-15 20:40:00 4491909392>
>>> timestring.Date('monday, aug 15th 2015 at 8:40 pm').date
datetime.datetime(2015, 8, 15, 20, 40)
>>> timestring.Range('next week')
<timestring.Range From 03/10/14 00:00:00 to 03/03/14 00:00:00 4496004880>
>>> (timestring.Range('next week').start.date, timestring.Range('next week').end.date)
(datetime.datetime(2014, 3, 10, 0, 0), datetime.datetime(2014, 3, 14, 0, 0))

@brandonjp 2014-04-11 05:09:18

Wow. Wow. Wow. Wow. This is so easy. I've got a datetime string and I just want to pull out the year. As simple as: import timestring timestring.Date('27 Mar 2014 12:32:29 GMT').year This lib made it SO EASY! Thank you.

@Steve Peak 2014-04-14 14:30:22

Your very welcome. I would love your comments and ideas on improving this package. Let me know, use github issues. Thanks!

@arctelix 2014-10-22 19:58:47

@Steve Peak timestring works great! Needed to parse article dates with scrapy and this has been converting them perfectly.

@Anake 2014-10-23 10:00:58

Hi steve, the module is great. Would be nice to have a weekday string attribute as well. Otherwise not sure if you start from Monday or Sunday

@Steve Peak 2014-10-25 22:22:01

@Anake you can create an issue to request this added at github.com/stevepeak/timestring thanks!

@drevicko 2014-11-07 00:09:11

Looks very interesting.. would be even more awesome if it incorporated dateutil's parser (and perhaps some other goodies). Nice work though (:

@fiatjaf 2015-02-09 21:11:53

The concept of a Range is very nice.

@Flowpoke 2015-02-10 19:53:21

This is an excellent package. Range is insanely powerful. How would you convert the timestring object to a datetime? I'd like to strip the time off, but .date() is not available.

@Steve Peak 2015-02-10 22:18:51

Yes. timestring.Range('this week').start and timestring.Range('this week').end

@Mr. Girgitt 2015-06-06 22:15:52

This module is very convenient to use. However be aware of not-so-great performance. Profiling result on i7 laptop: Python\Python27\site-packages\timestring\Date.py.__init__:20 2458 1.42 0.41 (ncall ttot tsub) It takes over 1.4 sec to perform 2400 timestring.Date('19:36:23 06/05/2015').to_unixtime() calls

@Patrick 2016-11-04 22:27:43

The ability to recognize all sorts of input here is really fantastic. A great addition is if it could also recognize less formal time ranges like "5-6pm". And then even better would be the ability to recognize the style of time ranges frequently used in text message conversations like "530pm-6" (without necessarily having colons or am/pm for both times).

@hobs 2017-06-06 23:44:27

WARNING: timestring doesn't yet correctly process subsecond times: timestring.Date('Aug 28 1999 12:53:45.123 AM').date gives datetime.datetime(1999, 8, 28, 0, 53, 45, 0) but dateutil.parser.parse('Aug 28 1999 12:53:45.123 AM') correctly gives datetime.datetime(1999, 8, 28, 0, 53, 45, 123)

@Anarach 2017-06-27 14:32:20

I was like this will not work but after i tried using it ,"YOU ARE A PROGRAMMING GOD" kind sir. Keep up the good work.. This is how a python package should work..

@Shule 2017-08-10 10:13:23

It doesn't convert such as '5 Feb 2017' and '5 February 2017' properly (which are formats popular in some circles, and IMO some of the best date formats for clarity and readability). It stores them as 2017-02-01. Same for 5/Feb/2017 (it does Feb/5/2017 correctly, however); neither of those last two are formats I've ever seen used to my knowledge, but I thought I'd point it out anyway.

@florin 2009-01-21 18:07:17

Check out strptime in the time module. It is the inverse of strftime.

$ python
>>> import time
>>> time.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')
time.struct_time(tm_year=2005, tm_mon=6, tm_mday=1,
                 tm_hour=13, tm_min=33, tm_sec=0,
                 tm_wday=2, tm_yday=152, tm_isdst=-1)

@Alexander Bird 2010-09-07 13:08:53

From what I understand, this answer only outputs time objects, not datetime objects -- which is why the answer would be buried compared to Patrick's answer.

@Anatoly G 2011-06-19 19:56:40

the answer below (by Patrick Harrington) is more correct, because time.strptime only outputs time, not datetime

@Hafiz 2012-09-15 18:21:41

strptime is handy when we already know the format, I wonder if there is something like php's strtotime that don't need to tell input format?

@kingpin 2013-01-22 15:50:05

Is there a way to set the default datetime format of the DateTimeField ?

@Leandro Alves 2013-03-09 15:20:44

As Alexander said, this return a struct_time, not a datetime. Of course you can convert it to a datetime, but Patrick's answer is more straight forward if you want a datetime object in the end.

@Geoff Gerrietts 2013-11-15 05:47:22

There's nothing like strtotime in the standard python library, but dateutil has a parser that recognizes a lot of best effort date formats.

@hobbes3 2014-01-27 23:20:39

Random question: How do you actually pronounce strptime and strftime? I'm assuming str is string and time is, well, time. So what's the p and f then?

@jfs 2014-04-29 10:54:36

@BenBlank: '%b', '%p' may fail in non-English locale.

@Chenming Zhang 2014-06-16 00:55:32

WARNNING!! I found it is very difficult to manipulate the time data in time.struct_time object. e.g., if you want to add particular days to that object, you have to convert time.struct_time object to datetime.datetime object. no other way around

@ᴠɪɴᴄᴇɴᴛ 2014-10-22 12:07:58

@hobbes3 parse and format.

@Simon Willison 2009-01-22 18:27:18

Use the third party dateutil library:

from dateutil import parser
dt = parser.parse("Aug 28 1999 12:00AM")

It can handle most date formats, including the one you need to parse. It's more convenient than strptime as it can guess the correct format most of the time.

It very useful for writing tests, where readability is more important than performance.

You can install it with:

pip install python-dateutil

@Paweł Polewicz 2011-07-03 00:08:39

Be aware that for large data amounts this might not be the most optimal way to approach the problem. Guessing the format every single time may be horribly slow.

@brian buck 2011-10-12 20:33:58

This is nice but it would be nice to have a solution that is built-in rather than having to go to a third party.

@Kartik Domadiya 2013-03-06 06:11:11

When I try to parse "32nd jan", it returns me "2032-01-06".. which is incorrect. is there any way to check whether the string is a valid date or not

@Antony Hatchkins 2013-04-30 18:19:54

@Reef: 5 times as slow according to my quick and dirty benchmark. Not so horribly slow as I would expect.

@Simon Tewsi 2013-11-28 21:11:17

Note that the current version of dateutil, version 2.2, depends on the six library, which is a Python 2/3 compatibility library. This allows dateutil 2.2 to work with both Python 2.x and Python 3.x.

@F1Rumors 2015-05-18 15:42:16

Has its own issues - like, for example, silently dropping time zone information from times: try parser.parse('15:55EST') and compare with parser.parse('15.55CST') as an example

@Chris Johnson 2016-02-27 14:07:50

This library is installed via pip install python-dateutil but used via import dateutil. This is one of the rare libraries that has a different name for pip purposes.

@Oli 2016-04-12 07:20:19

This has a very unfortunate habit of getting confused between US and UK dmy and mdy formats.. But it is handy when you're being lazy or have to juggle many formats.

@Thomas Kimber 2018-02-10 00:06:58

Great answer - nice module (I was dreading having to write something like this myself!) Is there any way to encourage dateutil to prefer British over American date styling? Something I could use it nudge it one way or another under different circumstances? edit - looks like the docs cover this using the dayfirst keyword

@Ryu_hayabusa 2014-11-20 17:58:01

Django Timezone aware datetime object example.

import datetime
from django.utils.timezone import get_current_timezone
tz = get_current_timezone()

format = '%b %d %Y %I:%M%p'
date_object = datetime.datetime.strptime('Jun 1 2005  1:33PM', format)
date_obj = tz.localize(date_object)

This conversion is very important for Django and Python when you have USE_TZ = True:

RuntimeWarning: DateTimeField MyModel.created received a naive datetime (2016-03-04 00:00:00) while time zone support is active.

@shadi 2018-09-10 04:09:22

So your point is to use tz.localize?

@guneysus 2016-01-19 07:48:47

In [34]: import datetime

In [35]: _now = datetime.datetime.now()

In [36]: _now
Out[36]: datetime.datetime(2016, 1, 19, 9, 47, 0, 432000)

In [37]: print _now
2016-01-19 09:47:00.432000

In [38]: _parsed = datetime.datetime.strptime(str(_now),"%Y-%m-%d %H:%M:%S.%f")

In [39]: _parsed
Out[39]: datetime.datetime(2016, 1, 19, 9, 47, 0, 432000)

In [40]: assert _now == _parsed

@Janus Troelsen 2014-03-06 11:53:05

Many timestamps have an implied timezone. To ensure that your code will work in every timezone, you should use UTC internally and attach a timezone each time a foreign object enters the system.

Python 3.2+:

>>> datetime.datetime.strptime(
...     "March 5, 2014, 20:13:50", "%B %d, %Y, %H:%M:%S"
... ).replace(tzinfo=datetime.timezone(datetime.timedelta(hours=-3)))

@jfs 2014-09-14 17:36:09

Why do you keep the ugly and sometimes wrong (mktime() during DST transitions) 1st method if you know the 2nd method (datetime.strptime())? If you want to avoid an exception during a leap second (the 2nd method fails) then you could use calendar.timegm instead: (datetime(1970,1,1)+timedelta(seconds=timegm(time.strptime(.‌​.)))).replace(tzinfo‌​=timezone(timedelta(‌​-3)))

@Raphael Amoedo 2015-06-01 15:15:02

You can use easy_date to make it easy:

import date_converter
converted_date = date_converter.string_to_datetime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

@Aram Kocharyan 2011-10-14 00:13:28

Something that isn't mentioned here and is useful: adding a suffix to the day. I decoupled the suffix logic so you can use it for any number you like, not just dates.

import time

def num_suffix(n):
    '''
    Returns the suffix for any given int
    '''
    suf = ('th','st', 'nd', 'rd')
    n = abs(n) # wise guy
    tens = int(str(n)[-2:])
    units = n % 10
    if tens > 10 and tens < 20:
        return suf[0] # teens with 'th'
    elif units <= 3:
        return suf[units]
    else:
        return suf[0] # 'th'

def day_suffix(t):
    '''
    Returns the suffix of the given struct_time day
    '''
    return num_suffix(t.tm_mday)

# Examples
print num_suffix(123)
print num_suffix(3431)
print num_suffix(1234)
print ''
print day_suffix(time.strptime("1 Dec 00", "%d %b %y"))
print day_suffix(time.strptime("2 Nov 01", "%d %b %y"))
print day_suffix(time.strptime("3 Oct 02", "%d %b %y"))
print day_suffix(time.strptime("4 Sep 03", "%d %b %y"))
print day_suffix(time.strptime("13 Nov 90", "%d %b %y"))
print day_suffix(time.strptime("14 Oct 10", "%d %b %y"))​​​​​​​

Related Questions

Sponsored Content

13 Answered Questions

[SOLVED] How to substring a string in Python?

  • 2009-03-19 17:29:41
  • Joan Venge
  • 2443318 View
  • 1821 Score
  • 13 Answer
  • Tags:   python string

42 Answered Questions

[SOLVED] How to return only the Date from a SQL Server DateTime datatype

36 Answered Questions

[SOLVED] Should I use the datetime or timestamp data type in MySQL?

14 Answered Questions

[SOLVED] Converting unix timestamp string to readable date

13 Answered Questions

[SOLVED] Converting a String to DateTime

  • 2009-05-28 05:01:02
  • dban
  • 1152610 View
  • 506 Score
  • 13 Answer
  • Tags:   c# datetime

17 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

16 Answered Questions

[SOLVED] Convert bytes to a string?

10 Answered Questions

[SOLVED] Convert date to datetime in Python

9 Answered Questions

[SOLVED] Converting integer to string in Python?

  • 2009-06-07 10:22:38
  • Hick
  • 2971831 View
  • 1173 Score
  • 9 Answer
  • Tags:   python

6 Answered Questions

[SOLVED] How do I convert datetime to date (in Python)?

  • 2010-09-18 19:44:01
  • niklasfi
  • 367178 View
  • 512 Score
  • 6 Answer
  • Tags:   python datetime

Sponsored Content