This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Converting string into datetime
I got log entries like:
2013-01-09 06:13:51,464 DEBUG module 159 Djang...
What is the shortest (best) way to extract the date from this string?
Do you need to keep the microsecond?
>>> import re
>>> log = "2013-01-09 06:13:51,464 DEBUG module"
>>> p = re.compile("\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d*")
>>> time_str = p.findall(log)[0]
>>> time_str
'2013-01-09 06:13:51,464'
>>> from datetime import datetime
>>> date_time = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S,%f')
>>> date_time
datetime.datetime(2013, 1, 9, 6, 13, 51, 464000)
from datetime import datetime
val = '2013-01-09 06:13:51,464'.split(',')[0] # Remove milliseconds
date_object = datetime.strptime(val, '%Y-%m-%d %H:%M:%S')
>>> a = "2013-01-09 06:13:51,464 DEBUG module"
>>> a = a.split(" ")
>>> date,time = a[0], a[1]
>>> date = date.split("-")
>>> time = time.split(",")[0].split(":")
>>> date
['2013', '01', '09']
>>> time
['06', '13', '51']
>>> args_list = [int(i) for i in date]
>>> args_list.extend( [int(i) for i in time])
>>> args_list
[2013, 1, 9, 6, 13, 51]
>>> import datetime
>>> datetime.datetime(*args_list)
datetime.datetime(2013, 1, 9, 6, 13, 51)
Related
date_str = '2022-03-29T17:49:35.914417-04:00'
How to compare above date string with current date time?
Try using datetime.fromisoformat(date_string) to parse date_str and then passing the determined timezone info into datetime.now(tz=None):
>>> from datetime import datetime
>>> date_str = '2022-03-29T17:49:35.914417-04:00'
>>> dt = datetime.fromisoformat(date_str)
>>> dt
datetime.datetime(2022, 3, 29, 17, 49, 35, 914417, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
>>> dt_now = datetime.now(dt.tzinfo)
>>> dt_now
datetime.datetime(2022, 5, 20, 15, 50, 58, 525908, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
>>> dt_now > dt
True
>>> dt_now - dt
datetime.timedelta(days=51, seconds=79282, microseconds=611491)
I have a date time format where dates are represented as integers from 1/1/1900 .
For example: 1 is 1/1/1900 and 42998 is 20/9/2017.
How can I convert this format to a human readable format like dd/mm/yyyy ? I checked datetime documentation but I did not find any way to do this. I want to do this either on python 3 or 2.7.
Thanks for any suggestion.
You can define your dates as offsets from your basetime and construct a datetime:
In[22]:
import datetime as dt
dt.datetime(1900,1,1) + dt.timedelta(42998)
Out[22]: datetime.datetime(2017, 9, 22, 0, 0)
Once it's a datetime object you can convert this to a str via strftime using whatever format you desire:
In[24]:
(dt.datetime(1900,1,1) + dt.timedelta(42998-1)).strftime('%d/%m/%Y')
Out[24]: '21/09/2017'
So you can define a user func to do this:
In[27]:
def dtToStr(val):
base = dt.datetime(1900,1,1)
return (base + dt.timedelta(val-1)).strftime('%d/%m/%Y')
dtToStr(42998)
Out[27]: '21/09/2017'
import datetime
base_date = datetime.datetime(1900, 1, 1)
convert = lambda x: base_date + datetime.timedelta(days=x-1)
>>> convert(42998)
datetime.datetime(2017, 9, 21, 0, 0)
You can use a datetime object to do that.
import datetime
d = datetime.datetime(1900, 1, 1, 0, 0)
d + datetime.timedelta(days = 42998)
>> datetime.datetime(2017, 9, 22, 0, 0)
How can I convert 'Jan' to an integer using Datetime? When I try strptime, I get an error time data 'Jan' does not match format '%m'
You have an abbreviated month name, so use %b:
>>> from datetime import datetime
>>> datetime.strptime('Jan', '%b')
datetime.datetime(1900, 1, 1, 0, 0)
>>> datetime.strptime('Aug', '%b')
datetime.datetime(1900, 8, 1, 0, 0)
>>> datetime.strptime('Jan 15 2015', '%b %d %Y')
datetime.datetime(2015, 1, 15, 0, 0)
%m is for a numeric month.
However, if all you wanted to do was map an abbreviated month to a number, just use a dictionary. You can build one from calendar.month_abbr:
import calendar
abbr_to_num = {name: num for num, name in enumerate(calendar.month_abbr) if num}
Demo:
>>> import calendar
>>> abbr_to_num = {name: num for num, name in enumerate(calendar.month_abbr) if num}
>>> abbr_to_num['Jan']
1
>>> abbr_to_num['Aug']
8
This is straightforward enough that you could consider just using a dictionary, then you have fewer dependencies anyway.
months = dict(Jan=1, Feb=2, Mar=3, ...)
print(months['Jan'])
>>> 1
Off the cuff-
Did you try %b?
from calendar import month_abbr
month = "Jun"
for k, v in enumerate(month_abbr):
if v == month:
month = k
break
print(month)
6
You will get the number of month 6
I have some strings which come to me in formats like
29-Jul-2014 or 03-Aug-2015
What is the easiest way to convert this to a datetime.date object?
I can only think to make a dictionary like d = {'Jul': 7, 'Aug': 8, ...} and then do
dt = datetime.date(year, d[month], day)
Is there any other easier way and avoid the creation of this dictionary?
Thanks
Use datetime.datetime.strptime to convert the string to datetime.datetime object.
>>> datetime.datetime.strptime('29-Jul-2014', '%d-%b-%Y')
datetime.datetime(2014, 7, 29, 0, 0)
Then, use datetime.datetime.date method to convert it to datetime.date object:
>>> datetime.datetime.strptime('29-Jul-2014', '%d-%b-%Y').date()
datetime.date(2014, 7, 29)
The easy way is use dateutil.parse module, it lets to parse the common date formats, even if you don't know what it is using currently
Ex:
>>> import dateutil.parser
>>>
>>> utc_time = '2014-07-29T00:00:00'
>>> verbose_time = '29-Jul-2014'
>>> some_locale = '29/7/14'
>>> dateutil.parser.parse(utc_time)
datetime.datetime(2014, 7, 29, 0, 0)
>>> dateutil.parser.parse(verbose_time)
datetime.datetime(2014, 7, 29, 0, 0)
>>> dateutil.parser.parse(some_locale)
datetime.datetime(2014, 7, 29, 0, 0)
Once you have a datetime object, you only should invoke the datetime.date() method
I am trying to convert a timestamp tuple from dpkt to a datetime instance.
The timestamp looks like (seconds, microseconds). This is what I am currently doing, but it seems overkill:
from datetime import datetime as dt
ts = (1296770576, 247792)
ts_list = [str(item) for item in ts]
ts_list[1] = ts_list[1].zfill(6) #make sure we have 6 digits
ts_str = ".".join(ts_list)
ts_float = float(ts_str)
ts_dt = dt.fromtimestamp(ts_float)
Is there a simpler way?
Just use the seconds part, then update the datetime object with the microseconds part, using the .replace() method:
dt.fromtimestamp(ts[0]).replace(microsecond=ts[1])
Demo:
>>> from datetime import datetime as dt
>>> ts = (1296770576, 247792)
>>> dt.fromtimestamp(ts[0]).replace(microsecond=ts[1])
datetime.datetime(2011, 2, 3, 23, 2, 56, 247792)
If you did ever have to convert your (seconds, microseconds) tuple to a float timestamp, just use floating-point division instead:
>>> ts_float = float(ts[0]) + float(ts[1]) / 1000000
>>> dt.fromtimestamp(ts_float)
datetime.datetime(2011, 2, 3, 23, 2, 56, 247792)