Converting string into datetime
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.
python datetime
add a comment |
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.
python datetime
2
for converting whole column with date-value strings ref to the option given in another post
– Joshua Baboo
Apr 22 '16 at 19:38
Unless you're sure one format handles every single date-time (no '', no NaNs, no incompletes, no format mismatches, no trailing characters, timezones, microsecond timestamps, or other text...), the exception-happiness ofstrptime()
will drive you nuts, unless you wrap it. See my answer, based on Or Weis answer to this
– smci
Dec 15 '17 at 3:00
add a comment |
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.
python datetime
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.
python datetime
python datetime
edited Jun 11 '16 at 15:33
Maxime Lorant
20.5k126376
20.5k126376
asked Jan 21 '09 at 18:00
Oli
118k52180255
118k52180255
2
for converting whole column with date-value strings ref to the option given in another post
– Joshua Baboo
Apr 22 '16 at 19:38
Unless you're sure one format handles every single date-time (no '', no NaNs, no incompletes, no format mismatches, no trailing characters, timezones, microsecond timestamps, or other text...), the exception-happiness ofstrptime()
will drive you nuts, unless you wrap it. See my answer, based on Or Weis answer to this
– smci
Dec 15 '17 at 3:00
add a comment |
2
for converting whole column with date-value strings ref to the option given in another post
– Joshua Baboo
Apr 22 '16 at 19:38
Unless you're sure one format handles every single date-time (no '', no NaNs, no incompletes, no format mismatches, no trailing characters, timezones, microsecond timestamps, or other text...), the exception-happiness ofstrptime()
will drive you nuts, unless you wrap it. See my answer, based on Or Weis answer to this
– smci
Dec 15 '17 at 3:00
2
2
for converting whole column with date-value strings ref to the option given in another post
– Joshua Baboo
Apr 22 '16 at 19:38
for converting whole column with date-value strings ref to the option given in another post
– Joshua Baboo
Apr 22 '16 at 19:38
Unless you're sure one format handles every single date-time (no '', no NaNs, no incompletes, no format mismatches, no trailing characters, timezones, microsecond timestamps, or other text...), the exception-happiness of
strptime()
will drive you nuts, unless you wrap it. See my answer, based on Or Weis answer to this– smci
Dec 15 '17 at 3:00
Unless you're sure one format handles every single date-time (no '', no NaNs, no incompletes, no format mismatches, no trailing characters, timezones, microsecond timestamps, or other text...), the exception-happiness of
strptime()
will drive you nuts, unless you wrap it. See my answer, based on Or Weis answer to this– smci
Dec 15 '17 at 3:00
add a comment |
19 Answers
19
active
oldest
votes
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:
Python documentation for
strptime
: Python 2, Python 3Python documentation for
strptime
/strftime
format strings: Python 2, Python 3strftime.org is also a really nice reference for strftime
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.
14
why does that return a date_object and not a datetime_object?
– jononomo
Apr 28 '14 at 19:07
4
'%b', '%p' may fail in non-English locale.
– jfs
Apr 29 '14 at 10:55
8
@User You'll have to know ahead of time to exclude that part of the format string, but if you want adate
instead of adatetime
, going throughdatetime
handles it nicely:datetime.strptime('Jun 1 2005', '%b %d %Y').date() == date(2005, 6, 1)
– Izkata
Nov 11 '14 at 20:02
5
If you know the string represents a datetime in UTC, you can get a timezone awaredatetime
object by adding this line in Python 3:from datetime import timezone; datetime_object = datetime_object.replace(tzinfo=timezone.utc)
– Flimm
Dec 8 '16 at 10:28
34
I was looking for"%Y-%m-%d %H:%M:%S"
– Martin Thoma
Dec 7 '17 at 13:56
|
show 8 more comments
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
67
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.
– Paweł Polewicz
Jul 3 '11 at 0:08
11
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.
– brian buck
Oct 12 '11 at 20:33
1
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
– Kartik Domadiya
Mar 6 '13 at 6:11
6
@Reef: 5 times as slow according to my quick and dirty benchmark. Not so horribly slow as I would expect.
– Antony Hatchkins
Apr 30 '13 at 18:19
2
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
– F1Rumors
May 18 '15 at 15:42
|
show 4 more comments
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)
15
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.
– Alexander Bird
Sep 7 '10 at 13:08
13
the answer below (by Patrick Harrington) is more correct, because time.strptime only outputs time, not datetime
– Anatoly G
Jun 19 '11 at 19:56
3
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.
– Leandro Alves
Mar 9 '13 at 15:20
1
@BenBlank: '%b', '%p' may fail in non-English locale.
– jfs
Apr 29 '14 at 10:54
1
@hobbes3parse
andformat
.
– ᴠɪɴᴄᴇɴᴛ
Oct 22 '14 at 12:07
|
show 5 more comments
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))
2
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.
– brandonjp
Apr 11 '14 at 5:09
Your very welcome. I would love your comments and ideas on improving this package. Let me know, use github issues. Thanks!
– Steve Peak
Apr 14 '14 at 14:30
@Steve Peak timestring works great! Needed to parse article dates with scrapy and this has been converting them perfectly.
– arctelix
Oct 22 '14 at 19: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
– Anake
Oct 23 '14 at 10:00
@Anake you can create an issue to request this added at github.com/stevepeak/timestring thanks!
– Steve Peak
Oct 25 '14 at 22:22
|
show 9 more comments
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)]
%S for Seconds as decimal
– optimist
Jun 9 '17 at 5:42
1
Won’t%b
break if you parse an English date on a machine that doesn’t have an English locale?
– bfontaine
May 8 at 9:44
add a comment |
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)))
3
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 usecalendar.timegm
instead:(datetime(1970,1,1)+timedelta(seconds=timegm(time.strptime(..)))).replace(tzinfo=timezone(timedelta(-3)))
– jfs
Sep 14 '14 at 17:36
add a comment |
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"))
add a comment |
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
add a comment |
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.
So your point is to usetz.localize
?
– shadi
Sep 10 at 4:09
add a comment |
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. However, 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.
add a comment |
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
add a comment |
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.
1
format
is a reserved word in python and shouldn't be used as a variable name.
– shredding
Jan 10 '17 at 9:30
add a comment |
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
add a comment |
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.
add a comment |
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')
add a comment |
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')
add a comment |
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.
add a comment |
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)
I needed a datetime string with timezone 👌
– Harry Moreno
Aug 29 at 19:59
add a comment |
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
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.
– RoG
Oct 2 at 12:28
@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.
– smci
Oct 2 at 19:38
"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.
– RoG
Oct 3 at 7:28
add a comment |
protected by casperOne Apr 26 '12 at 12:03
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
19 Answers
19
active
oldest
votes
19 Answers
19
active
oldest
votes
active
oldest
votes
active
oldest
votes
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:
Python documentation for
strptime
: Python 2, Python 3Python documentation for
strptime
/strftime
format strings: Python 2, Python 3strftime.org is also a really nice reference for strftime
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.
14
why does that return a date_object and not a datetime_object?
– jononomo
Apr 28 '14 at 19:07
4
'%b', '%p' may fail in non-English locale.
– jfs
Apr 29 '14 at 10:55
8
@User You'll have to know ahead of time to exclude that part of the format string, but if you want adate
instead of adatetime
, going throughdatetime
handles it nicely:datetime.strptime('Jun 1 2005', '%b %d %Y').date() == date(2005, 6, 1)
– Izkata
Nov 11 '14 at 20:02
5
If you know the string represents a datetime in UTC, you can get a timezone awaredatetime
object by adding this line in Python 3:from datetime import timezone; datetime_object = datetime_object.replace(tzinfo=timezone.utc)
– Flimm
Dec 8 '16 at 10:28
34
I was looking for"%Y-%m-%d %H:%M:%S"
– Martin Thoma
Dec 7 '17 at 13:56
|
show 8 more comments
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:
Python documentation for
strptime
: Python 2, Python 3Python documentation for
strptime
/strftime
format strings: Python 2, Python 3strftime.org is also a really nice reference for strftime
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.
14
why does that return a date_object and not a datetime_object?
– jononomo
Apr 28 '14 at 19:07
4
'%b', '%p' may fail in non-English locale.
– jfs
Apr 29 '14 at 10:55
8
@User You'll have to know ahead of time to exclude that part of the format string, but if you want adate
instead of adatetime
, going throughdatetime
handles it nicely:datetime.strptime('Jun 1 2005', '%b %d %Y').date() == date(2005, 6, 1)
– Izkata
Nov 11 '14 at 20:02
5
If you know the string represents a datetime in UTC, you can get a timezone awaredatetime
object by adding this line in Python 3:from datetime import timezone; datetime_object = datetime_object.replace(tzinfo=timezone.utc)
– Flimm
Dec 8 '16 at 10:28
34
I was looking for"%Y-%m-%d %H:%M:%S"
– Martin Thoma
Dec 7 '17 at 13:56
|
show 8 more comments
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:
Python documentation for
strptime
: Python 2, Python 3Python documentation for
strptime
/strftime
format strings: Python 2, Python 3strftime.org is also a really nice reference for strftime
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.
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:
Python documentation for
strptime
: Python 2, Python 3Python documentation for
strptime
/strftime
format strings: Python 2, Python 3strftime.org is also a really nice reference for strftime
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.
edited Apr 28 at 6:17
user2357112
150k12157247
150k12157247
answered Jan 21 '09 at 18:08
Patrick Harrington
29.3k41919
29.3k41919
14
why does that return a date_object and not a datetime_object?
– jononomo
Apr 28 '14 at 19:07
4
'%b', '%p' may fail in non-English locale.
– jfs
Apr 29 '14 at 10:55
8
@User You'll have to know ahead of time to exclude that part of the format string, but if you want adate
instead of adatetime
, going throughdatetime
handles it nicely:datetime.strptime('Jun 1 2005', '%b %d %Y').date() == date(2005, 6, 1)
– Izkata
Nov 11 '14 at 20:02
5
If you know the string represents a datetime in UTC, you can get a timezone awaredatetime
object by adding this line in Python 3:from datetime import timezone; datetime_object = datetime_object.replace(tzinfo=timezone.utc)
– Flimm
Dec 8 '16 at 10:28
34
I was looking for"%Y-%m-%d %H:%M:%S"
– Martin Thoma
Dec 7 '17 at 13:56
|
show 8 more comments
14
why does that return a date_object and not a datetime_object?
– jononomo
Apr 28 '14 at 19:07
4
'%b', '%p' may fail in non-English locale.
– jfs
Apr 29 '14 at 10:55
8
@User You'll have to know ahead of time to exclude that part of the format string, but if you want adate
instead of adatetime
, going throughdatetime
handles it nicely:datetime.strptime('Jun 1 2005', '%b %d %Y').date() == date(2005, 6, 1)
– Izkata
Nov 11 '14 at 20:02
5
If you know the string represents a datetime in UTC, you can get a timezone awaredatetime
object by adding this line in Python 3:from datetime import timezone; datetime_object = datetime_object.replace(tzinfo=timezone.utc)
– Flimm
Dec 8 '16 at 10:28
34
I was looking for"%Y-%m-%d %H:%M:%S"
– Martin Thoma
Dec 7 '17 at 13:56
14
14
why does that return a date_object and not a datetime_object?
– jononomo
Apr 28 '14 at 19:07
why does that return a date_object and not a datetime_object?
– jononomo
Apr 28 '14 at 19:07
4
4
'%b', '%p' may fail in non-English locale.
– jfs
Apr 29 '14 at 10:55
'%b', '%p' may fail in non-English locale.
– jfs
Apr 29 '14 at 10:55
8
8
@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)
– Izkata
Nov 11 '14 at 20:02
@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)
– Izkata
Nov 11 '14 at 20:02
5
5
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)
– Flimm
Dec 8 '16 at 10:28
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)
– Flimm
Dec 8 '16 at 10:28
34
34
I was looking for
"%Y-%m-%d %H:%M:%S"
– Martin Thoma
Dec 7 '17 at 13:56
I was looking for
"%Y-%m-%d %H:%M:%S"
– Martin Thoma
Dec 7 '17 at 13:56
|
show 8 more comments
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
67
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.
– Paweł Polewicz
Jul 3 '11 at 0:08
11
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.
– brian buck
Oct 12 '11 at 20:33
1
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
– Kartik Domadiya
Mar 6 '13 at 6:11
6
@Reef: 5 times as slow according to my quick and dirty benchmark. Not so horribly slow as I would expect.
– Antony Hatchkins
Apr 30 '13 at 18:19
2
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
– F1Rumors
May 18 '15 at 15:42
|
show 4 more comments
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
67
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.
– Paweł Polewicz
Jul 3 '11 at 0:08
11
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.
– brian buck
Oct 12 '11 at 20:33
1
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
– Kartik Domadiya
Mar 6 '13 at 6:11
6
@Reef: 5 times as slow according to my quick and dirty benchmark. Not so horribly slow as I would expect.
– Antony Hatchkins
Apr 30 '13 at 18:19
2
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
– F1Rumors
May 18 '15 at 15:42
|
show 4 more comments
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
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
edited Mar 23 '16 at 16:35
Decko
10k21933
10k21933
answered Jan 22 '09 at 18:27
Simon Willison
9,63852940
9,63852940
67
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.
– Paweł Polewicz
Jul 3 '11 at 0:08
11
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.
– brian buck
Oct 12 '11 at 20:33
1
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
– Kartik Domadiya
Mar 6 '13 at 6:11
6
@Reef: 5 times as slow according to my quick and dirty benchmark. Not so horribly slow as I would expect.
– Antony Hatchkins
Apr 30 '13 at 18:19
2
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
– F1Rumors
May 18 '15 at 15:42
|
show 4 more comments
67
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.
– Paweł Polewicz
Jul 3 '11 at 0:08
11
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.
– brian buck
Oct 12 '11 at 20:33
1
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
– Kartik Domadiya
Mar 6 '13 at 6:11
6
@Reef: 5 times as slow according to my quick and dirty benchmark. Not so horribly slow as I would expect.
– Antony Hatchkins
Apr 30 '13 at 18:19
2
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
– F1Rumors
May 18 '15 at 15:42
67
67
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.
– Paweł Polewicz
Jul 3 '11 at 0:08
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.
– Paweł Polewicz
Jul 3 '11 at 0:08
11
11
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.
– brian buck
Oct 12 '11 at 20:33
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.
– brian buck
Oct 12 '11 at 20:33
1
1
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
– Kartik Domadiya
Mar 6 '13 at 6: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
– Kartik Domadiya
Mar 6 '13 at 6:11
6
6
@Reef: 5 times as slow according to my quick and dirty benchmark. Not so horribly slow as I would expect.
– Antony Hatchkins
Apr 30 '13 at 18:19
@Reef: 5 times as slow according to my quick and dirty benchmark. Not so horribly slow as I would expect.
– Antony Hatchkins
Apr 30 '13 at 18:19
2
2
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
– F1Rumors
May 18 '15 at 15:42
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
– F1Rumors
May 18 '15 at 15:42
|
show 4 more comments
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)
15
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.
– Alexander Bird
Sep 7 '10 at 13:08
13
the answer below (by Patrick Harrington) is more correct, because time.strptime only outputs time, not datetime
– Anatoly G
Jun 19 '11 at 19:56
3
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.
– Leandro Alves
Mar 9 '13 at 15:20
1
@BenBlank: '%b', '%p' may fail in non-English locale.
– jfs
Apr 29 '14 at 10:54
1
@hobbes3parse
andformat
.
– ᴠɪɴᴄᴇɴᴛ
Oct 22 '14 at 12:07
|
show 5 more comments
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)
15
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.
– Alexander Bird
Sep 7 '10 at 13:08
13
the answer below (by Patrick Harrington) is more correct, because time.strptime only outputs time, not datetime
– Anatoly G
Jun 19 '11 at 19:56
3
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.
– Leandro Alves
Mar 9 '13 at 15:20
1
@BenBlank: '%b', '%p' may fail in non-English locale.
– jfs
Apr 29 '14 at 10:54
1
@hobbes3parse
andformat
.
– ᴠɪɴᴄᴇɴᴛ
Oct 22 '14 at 12:07
|
show 5 more comments
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)
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)
edited Dec 29 '16 at 18:50
Bruno Bronosky
33.4k47780
33.4k47780
answered Jan 21 '09 at 18:07
florin
11.4k53646
11.4k53646
15
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.
– Alexander Bird
Sep 7 '10 at 13:08
13
the answer below (by Patrick Harrington) is more correct, because time.strptime only outputs time, not datetime
– Anatoly G
Jun 19 '11 at 19:56
3
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.
– Leandro Alves
Mar 9 '13 at 15:20
1
@BenBlank: '%b', '%p' may fail in non-English locale.
– jfs
Apr 29 '14 at 10:54
1
@hobbes3parse
andformat
.
– ᴠɪɴᴄᴇɴᴛ
Oct 22 '14 at 12:07
|
show 5 more comments
15
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.
– Alexander Bird
Sep 7 '10 at 13:08
13
the answer below (by Patrick Harrington) is more correct, because time.strptime only outputs time, not datetime
– Anatoly G
Jun 19 '11 at 19:56
3
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.
– Leandro Alves
Mar 9 '13 at 15:20
1
@BenBlank: '%b', '%p' may fail in non-English locale.
– jfs
Apr 29 '14 at 10:54
1
@hobbes3parse
andformat
.
– ᴠɪɴᴄᴇɴᴛ
Oct 22 '14 at 12:07
15
15
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.
– Alexander Bird
Sep 7 '10 at 13:08
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.
– Alexander Bird
Sep 7 '10 at 13:08
13
13
the answer below (by Patrick Harrington) is more correct, because time.strptime only outputs time, not datetime
– Anatoly G
Jun 19 '11 at 19:56
the answer below (by Patrick Harrington) is more correct, because time.strptime only outputs time, not datetime
– Anatoly G
Jun 19 '11 at 19:56
3
3
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.
– Leandro Alves
Mar 9 '13 at 15:20
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.
– Leandro Alves
Mar 9 '13 at 15:20
1
1
@BenBlank: '%b', '%p' may fail in non-English locale.
– jfs
Apr 29 '14 at 10:54
@BenBlank: '%b', '%p' may fail in non-English locale.
– jfs
Apr 29 '14 at 10:54
1
1
@hobbes3
parse
and format
.– ᴠɪɴᴄᴇɴᴛ
Oct 22 '14 at 12:07
@hobbes3
parse
and format
.– ᴠɪɴᴄᴇɴᴛ
Oct 22 '14 at 12:07
|
show 5 more comments
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))
2
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.
– brandonjp
Apr 11 '14 at 5:09
Your very welcome. I would love your comments and ideas on improving this package. Let me know, use github issues. Thanks!
– Steve Peak
Apr 14 '14 at 14:30
@Steve Peak timestring works great! Needed to parse article dates with scrapy and this has been converting them perfectly.
– arctelix
Oct 22 '14 at 19: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
– Anake
Oct 23 '14 at 10:00
@Anake you can create an issue to request this added at github.com/stevepeak/timestring thanks!
– Steve Peak
Oct 25 '14 at 22:22
|
show 9 more comments
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))
2
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.
– brandonjp
Apr 11 '14 at 5:09
Your very welcome. I would love your comments and ideas on improving this package. Let me know, use github issues. Thanks!
– Steve Peak
Apr 14 '14 at 14:30
@Steve Peak timestring works great! Needed to parse article dates with scrapy and this has been converting them perfectly.
– arctelix
Oct 22 '14 at 19: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
– Anake
Oct 23 '14 at 10:00
@Anake you can create an issue to request this added at github.com/stevepeak/timestring thanks!
– Steve Peak
Oct 25 '14 at 22:22
|
show 9 more comments
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))
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))
edited Dec 29 '16 at 19:33
Bruno Bronosky
33.4k47780
33.4k47780
answered Mar 2 '14 at 14:22
Steve Peak
1,8871118
1,8871118
2
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.
– brandonjp
Apr 11 '14 at 5:09
Your very welcome. I would love your comments and ideas on improving this package. Let me know, use github issues. Thanks!
– Steve Peak
Apr 14 '14 at 14:30
@Steve Peak timestring works great! Needed to parse article dates with scrapy and this has been converting them perfectly.
– arctelix
Oct 22 '14 at 19: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
– Anake
Oct 23 '14 at 10:00
@Anake you can create an issue to request this added at github.com/stevepeak/timestring thanks!
– Steve Peak
Oct 25 '14 at 22:22
|
show 9 more comments
2
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.
– brandonjp
Apr 11 '14 at 5:09
Your very welcome. I would love your comments and ideas on improving this package. Let me know, use github issues. Thanks!
– Steve Peak
Apr 14 '14 at 14:30
@Steve Peak timestring works great! Needed to parse article dates with scrapy and this has been converting them perfectly.
– arctelix
Oct 22 '14 at 19: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
– Anake
Oct 23 '14 at 10:00
@Anake you can create an issue to request this added at github.com/stevepeak/timestring thanks!
– Steve Peak
Oct 25 '14 at 22:22
2
2
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.– brandonjp
Apr 11 '14 at 5:09
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.– brandonjp
Apr 11 '14 at 5:09
Your very welcome. I would love your comments and ideas on improving this package. Let me know, use github issues. Thanks!
– Steve Peak
Apr 14 '14 at 14:30
Your very welcome. I would love your comments and ideas on improving this package. Let me know, use github issues. Thanks!
– Steve Peak
Apr 14 '14 at 14:30
@Steve Peak timestring works great! Needed to parse article dates with scrapy and this has been converting them perfectly.
– arctelix
Oct 22 '14 at 19:58
@Steve Peak timestring works great! Needed to parse article dates with scrapy and this has been converting them perfectly.
– arctelix
Oct 22 '14 at 19: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
– Anake
Oct 23 '14 at 10:00
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
– Anake
Oct 23 '14 at 10:00
@Anake you can create an issue to request this added at github.com/stevepeak/timestring thanks!
– Steve Peak
Oct 25 '14 at 22:22
@Anake you can create an issue to request this added at github.com/stevepeak/timestring thanks!
– Steve Peak
Oct 25 '14 at 22:22
|
show 9 more comments
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)]
%S for Seconds as decimal
– optimist
Jun 9 '17 at 5:42
1
Won’t%b
break if you parse an English date on a machine that doesn’t have an English locale?
– bfontaine
May 8 at 9:44
add a comment |
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)]
%S for Seconds as decimal
– optimist
Jun 9 '17 at 5:42
1
Won’t%b
break if you parse an English date on a machine that doesn’t have an English locale?
– bfontaine
May 8 at 9:44
add a comment |
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)]
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)]
edited Jan 30 '17 at 7:20
answered Dec 10 '14 at 13:00
Rizwan Mumtaz
2,28721823
2,28721823
%S for Seconds as decimal
– optimist
Jun 9 '17 at 5:42
1
Won’t%b
break if you parse an English date on a machine that doesn’t have an English locale?
– bfontaine
May 8 at 9:44
add a comment |
%S for Seconds as decimal
– optimist
Jun 9 '17 at 5:42
1
Won’t%b
break if you parse an English date on a machine that doesn’t have an English locale?
– bfontaine
May 8 at 9:44
%S for Seconds as decimal
– optimist
Jun 9 '17 at 5:42
%S for Seconds as decimal
– optimist
Jun 9 '17 at 5:42
1
1
Won’t
%b
break if you parse an English date on a machine that doesn’t have an English locale?– bfontaine
May 8 at 9:44
Won’t
%b
break if you parse an English date on a machine that doesn’t have an English locale?– bfontaine
May 8 at 9:44
add a comment |
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)))
3
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 usecalendar.timegm
instead:(datetime(1970,1,1)+timedelta(seconds=timegm(time.strptime(..)))).replace(tzinfo=timezone(timedelta(-3)))
– jfs
Sep 14 '14 at 17:36
add a comment |
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)))
3
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 usecalendar.timegm
instead:(datetime(1970,1,1)+timedelta(seconds=timegm(time.strptime(..)))).replace(tzinfo=timezone(timedelta(-3)))
– jfs
Sep 14 '14 at 17:36
add a comment |
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)))
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)))
edited Jun 5 '15 at 12:34
answered Mar 6 '14 at 11:53
Janus Troelsen
13.4k595151
13.4k595151
3
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 usecalendar.timegm
instead:(datetime(1970,1,1)+timedelta(seconds=timegm(time.strptime(..)))).replace(tzinfo=timezone(timedelta(-3)))
– jfs
Sep 14 '14 at 17:36
add a comment |
3
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 usecalendar.timegm
instead:(datetime(1970,1,1)+timedelta(seconds=timegm(time.strptime(..)))).replace(tzinfo=timezone(timedelta(-3)))
– jfs
Sep 14 '14 at 17:36
3
3
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)))
– jfs
Sep 14 '14 at 17:36
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)))
– jfs
Sep 14 '14 at 17:36
add a comment |
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"))
add a comment |
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"))
add a comment |
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"))
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"))
edited Oct 14 '11 at 0:28
answered Oct 14 '11 at 0:13
Aram Kocharyan
16.1k106280
16.1k106280
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
edited Dec 2 '17 at 7:08
answered Dec 20 '15 at 3:03
Alexander
52.6k1287121
52.6k1287121
add a comment |
add a comment |
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.
So your point is to usetz.localize
?
– shadi
Sep 10 at 4:09
add a comment |
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.
So your point is to usetz.localize
?
– shadi
Sep 10 at 4:09
add a comment |
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.
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.
edited Mar 3 '16 at 13:44
Tarek Kalaji
1,0191723
1,0191723
answered Nov 20 '14 at 17:58
Ryu_hayabusa
2,01311825
2,01311825
So your point is to usetz.localize
?
– shadi
Sep 10 at 4:09
add a comment |
So your point is to usetz.localize
?
– shadi
Sep 10 at 4:09
So your point is to use
tz.localize
?– shadi
Sep 10 at 4:09
So your point is to use
tz.localize
?– shadi
Sep 10 at 4:09
add a comment |
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. However, 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.
add a comment |
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. However, 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.
add a comment |
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. However, 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.
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. However, 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.
edited May 23 at 23:06
Peter Mortensen
13.5k1983111
13.5k1983111
answered Jan 2 at 0:04
user1767754
9,40156981
9,40156981
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
answered Jan 19 '16 at 7:48
guneysus
3,92812929
3,92812929
add a comment |
add a comment |
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.
1
format
is a reserved word in python and shouldn't be used as a variable name.
– shredding
Jan 10 '17 at 9:30
add a comment |
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.
1
format
is a reserved word in python and shouldn't be used as a variable name.
– shredding
Jan 10 '17 at 9:30
add a comment |
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.
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.
edited May 23 at 23:00
Peter Mortensen
13.5k1983111
13.5k1983111
answered Feb 4 '16 at 13:43
Mackraken
23923
23923
1
format
is a reserved word in python and shouldn't be used as a variable name.
– shredding
Jan 10 '17 at 9:30
add a comment |
1
format
is a reserved word in python and shouldn't be used as a variable name.
– shredding
Jan 10 '17 at 9:30
1
1
format
is a reserved word in python and shouldn't be used as a variable name.– shredding
Jan 10 '17 at 9:30
format
is a reserved word in python and shouldn't be used as a variable name.– shredding
Jan 10 '17 at 9:30
add a comment |
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
add a comment |
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
add a comment |
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
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
edited May 23 at 23:01
Peter Mortensen
13.5k1983111
13.5k1983111
answered Jun 24 '16 at 4:07
Rajiv Sharma
2,0612033
2,0612033
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited May 23 at 23:02
Peter Mortensen
13.5k1983111
13.5k1983111
answered Feb 28 '17 at 17:37
Bill Bell
15.3k42542
15.3k42542
add a comment |
add a comment |
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')
add a comment |
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')
add a comment |
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')
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')
answered Oct 15 at 21:02
Toskan
5,00074994
5,00074994
add a comment |
add a comment |
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')
add a comment |
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')
add a comment |
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')
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')
answered Jun 1 '15 at 15:15
Raphael Amoedo
2,28411727
2,28411727
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited May 23 at 23:04
Peter Mortensen
13.5k1983111
13.5k1983111
answered Dec 21 '17 at 12:44
Javed
50569
50569
add a comment |
add a comment |
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)
I needed a datetime string with timezone 👌
– Harry Moreno
Aug 29 at 19:59
add a comment |
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)
I needed a datetime string with timezone 👌
– Harry Moreno
Aug 29 at 19:59
add a comment |
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)
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)
edited Aug 30 at 5:49
answered Aug 16 at 4:17
Kanish Mathew
293
293
I needed a datetime string with timezone 👌
– Harry Moreno
Aug 29 at 19:59
add a comment |
I needed a datetime string with timezone 👌
– Harry Moreno
Aug 29 at 19:59
I needed a datetime string with timezone 👌
– Harry Moreno
Aug 29 at 19:59
I needed a datetime string with timezone 👌
– Harry Moreno
Aug 29 at 19:59
add a comment |
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
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.
– RoG
Oct 2 at 12:28
@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.
– smci
Oct 2 at 19:38
"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.
– RoG
Oct 3 at 7:28
add a comment |
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
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.
– RoG
Oct 2 at 12:28
@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.
– smci
Oct 2 at 19:38
"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.
– RoG
Oct 3 at 7:28
add a comment |
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
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
edited Sep 5 at 15:52
answered Dec 18 '17 at 21:12
smci
14.6k672104
14.6k672104
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.
– RoG
Oct 2 at 12:28
@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.
– smci
Oct 2 at 19:38
"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.
– RoG
Oct 3 at 7:28
add a comment |
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.
– RoG
Oct 2 at 12:28
@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.
– smci
Oct 2 at 19:38
"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.
– RoG
Oct 3 at 7:28
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.
– RoG
Oct 2 at 12:28
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.
– RoG
Oct 2 at 12:28
@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.
– smci
Oct 2 at 19:38
@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.
– smci
Oct 2 at 19:38
"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.
– RoG
Oct 3 at 7:28
"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.
– RoG
Oct 3 at 7:28
add a comment |
protected by casperOne Apr 26 '12 at 12:03
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
2
for converting whole column with date-value strings ref to the option given in another post
– Joshua Baboo
Apr 22 '16 at 19:38
Unless you're sure one format handles every single date-time (no '', no NaNs, no incompletes, no format mismatches, no trailing characters, timezones, microsecond timestamps, or other text...), the exception-happiness of
strptime()
will drive you nuts, unless you wrap it. See my answer, based on Or Weis answer to this– smci
Dec 15 '17 at 3:00