from datetime import datetime
datetime.strptime('%b%d %I:%M%p', 'AUG21 3:26PM')
results with
1900-08-21 15:26:00
how can I write in pythonic way so that when there's no year, take the current year as default (2013)?
I checked and strftime function doesn't have option to change the default.. maybe another time libraries can do?
thx
Parse the date as you are already doing, and then
date= date.replace(2013)
This is one of simplest solution with the modules you are using.
Thinking better about it, you will probably face a problem next Feb 29.
input= 'Aug21 3:26PM'
output= datetime.datetime.strptime('2013 '+ input ,'%Y %b%d %I:%M%p')
You can find out today's date to replace year for dynamic replacement.
datetime.strptime('%b%d %I:%M%p', 'AUG21 3:26PM').replace(year=datetime.today().year)
Related
I need to return the date format from a string. Currently I am using parser to parse a string as a date, then replacing the year with a yyyy or yy. Similarly for other dates items. Is there some function I could use that would return mm-dd-yyyy when I send 12-05-2018?
Technically, it is an impossible question. If you send in 12-05-2018, there is no way for me to know whether you are sending in a mm-dd-yyyy (Dec 5, 2018) or dd-mm-yyyy (May 12, 2018).
One approach might be to do a regex replacement of anything which matches your expected date pattern, e.g.
date = "Here is a date: 12-05-2018 and here is another one: 10-31-2010"
date_masked = re.sub(r'\b\d{2}-\d{2}-\d{4}\b', 'mm-dd-yyyy', date)
print(date)
print(date_masked)
Here is a date: 12-05-2018 and here is another one: 10-31-2010
Here is a date: mm-dd-yyyy and here is another one: mm-dd-yyyy
Of course, the above script makes no effort to check whether the dates are actually valid. If you require that, you may use one of the date libraries available in Python.
I don't really understand what you plan to do with the format. There are two reasons I can think of why you might want it. (1) You want at some future point to convert a normalized datetime back into the original string. If that is what you want you would be better off just storing the normalized datetime and the original string. Or (2) you want to draw (dodgy) conclusions about person sending the data, because different nationalities will tend to use different formats. But, whatever you want it for, you can do it this way:
from dateutil import parser
def get_date_format(date_input):
date = parser.parse(date_input)
for date_format in ("%m-%d-%Y", "%d-%m-%Y", "%Y-%m-%d"):
# You can extend the list above to include formats with %y in addition to %Y, etc, etc
if date.strftime(date_format) == date_input:
return date_format
>>> date_input = "12-05-2018"
>>> get_date_format(date_input)
'%m-%d-%Y'
You mention in a comment you are prepared to make assumptions about ambiguous dates like 12-05-2018 (could be May or December) and 05-12-18 (could be 2018 or 2005). You can pass those assumptions to dateutil.parser.parse. It accepts boolean keyword parameters dayfirst and yearfirst which it will use in ambiguous cases.
Take a look at the datetime library. There you will find the function strptime(), which is exactly what you are looking for.
Here is the documentation: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
If I use the following command to localize my timestamp to "CET":
pd.Timestamp('2011-11-06 11:00:00').tz_localize('CET')
output: Timestamp('2011-11-06 11:00:00+0100', tz='CET')
if I use :
pd.Timestamp('2011-06-06 11:00:00').tz_localize('CET')
output: Timestamp('2011-06-06 11:00:00+0200', tz='CET')
So obviously it automatically convert into "CEST" in summer, am I right? what if I would like to keep my timestamp in "CET" through out the whole year (keep it UTC +1:00 all the time), what should I do? Thank you very much!
Updated:
the following seems working:
pd.Timestamp('2011-06-06 11:00:00').tz_localize(tz=pytz.FixedOffset(60))
output:Timestamp('2011-06-06 11:00:00+0100', tz='pytz.FixedOffset(60)')
any other suggestions?
I have a big .csv file which holds machine log data. One of the fields is timestamp. It stores date and time as shown in the title and I would like to drop the milli seconds and convert it into the format also shown in title. Can anyone help me with that? Im new to Python and Ipython.
Much obliged.
For your special case, this should suffice:
t.replace('T', ' ')[:19]
But I would recommend, that you use the datetime module of the standard library instead, so your time conversion also could be internationalized.
You can use easy_date to make it easy:
import date_converter
new_date = date_converter.string_to_string("2013-01-06T22:25:08.733", "%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%d %H:%M:%S")
For example I give the date as:
2/12/2015
The result should be:
February/Thursday/2015
I tried to do with if but I'm not getting the result. It would be nice if you could tell me the long way (without using built in functions (like datetime and others) too much). I'm new to python and not much is taught in my school.
You don't have to use datetime too much, simply parse the date and output it in whatever format you want
from datetime import datetime
d = "2/12/2015"
print(datetime.strptime(d,"%m/%d/%Y").strftime("%B/%A/%Y"))
February/Thursday/2015
A = Locale’s full weekday name.
B = Locale’s full month name.
Y = Year with century as a decimal number.
All the format directives are here
You could create a dict mapping but you will find datetime is lot simpler.
I'm astounded by some code I wrote some time ago. For not entering in much detail i have a method that runs through some objects, wich have a date parameter. If the date parameter is equal to today's date, goes on.
I have set this in my local machine for test and have like 695 objects all with the same date, today, but when the action is run nothing happens, so i debug it to find that my expression date.today() returns datetime.date(2014, 3, 19).
This is is incorrect, as the date of my computer from the date command is Tue Mar 18 20:56:09 AST 2014.
I used from datetime import date. This is one of the more cryptic errors i have ever got. Any experience someone can share here? Thanks a lot.
The method is not timezone aware and there's no platform-independent way to make it so. What is generally done is incorporate something like pytz and call .today() as:
datetime.utcnow().replace(tzinfo = pytz.utc).strftime('%Y-%m-%d')