I have a list of datetime object (let say datetime_obj) Now I want only its time part .
datetime_obj[0] = 22-Jun-23 13:32:00
I'm trying this :
time = [datetime.datetime.strptime(str(i)[11:], '%H:%M:%S') for I in datetime_obj]
But when I am printing time it showing 01-Jan-1900 13:32:00
Basically it is attaching a random date. what should I do?
You can directly call the ".strftime("%H:%M:%S")" method on your datetime object. This way you can avoid the list comprehension method you were using.
For example, the one-liner
print(datetime.datetime.now().strftime("%H:%M:%S"))
gives you the actual time printed in the format that you need from the datetime object datetime_obj=datetime.datetime.now()
If you need the values instead, you could access to the .hour, .minute and .second properties of datetime_obj.
Related
This is my data :
dates = np.arange("2018-01-01", "2021-12-31", dtype="datetime64[D]")
I now want to convert from :
"2018-01-01" -> "Jan-01-2018" ["Monthname-day-year"] format
How to i do this ?
Is it possible to initialize this in the way we want to convert ?
Can i use something like:
for i in dates:
i = i.replace(i.month,i.strftime("%b"))
You can try this:
from datetime import datetime
dates = np.arange("2018-01-01", "2021-12-31", dtype="datetime64[D]")
result_dates = []
for date in dates.astype(datetime):
result_dates.append(date.strftime("%b-%d-%Y"))
But you will need to convert result dates as shown in the code
I feel compelled to elaborate on Silvio Mayolo's very relevant but ostensibly ignored comment above. Python stores a timestamp as structure (see How does Python store datetime internally? for more information) Hence, the DateTime does not as such have a 'format'. A format only becomes necessary when you want to print the date because you must first convert the timestamp to a string. Thus, you do NOT need to initialise any format. You only need to declare a format when the time comes to print the timestamp.
While you CAN store the date as a string in your dataframe index in a specific format, you CANNOT perform time related functions on it without first converting the string back to a time variable. ie current_time.hour will return an integer with the current hour if current_time is a datetime variable but will crash if it is a string formatted as a timestamp (such as "2023-01-15 17:23").
This is important to understand, because eventually you will need to manipulate the variables and need to understand whether you are working with a time or a string.
I'm learning Pandas and I have a problem trying to change a format from Object to Date_time.
When I use 'to_datetime' the date I get in return is like in ISO Format, and I just want DD/MM/YYYY (13/10/1960). And I doing something wrong? Thanks a lot!!
enter image description here
At a glance, it doesn't seem like the code uses the right format.
The to_datetime() with the format argument follows strftime standards per the documentation here, and it's a way to tell the method how the original time was represented (so it can properly format it into a datetime object). An example can be seen from this Stack Overflow question.
Simple example:
datetime_object = pd.to_datetime(format='%d/%m/%Y')
The next problem is how you want that datetime object to be printed out (i.e. DD/MM/YYYY). Just throwing thoughts out there (would comment, but I don't have those privileges yet), if you want to print the string, you can cast that datetime object into the string that you want. Many ways to do this, one of which is to use strftime().
Simple example:
date_as_string = datetime_object.strftime('%d/%m/%Y')
But of course, why would you use a datetime object in that case. So the other option I can think of is to override how the datetime object is printed (redefining __str__ in a new class of datetime).
for testing purposes i want to compare two datetime objects.
dt1 = fake.date_time() # assumming 2021-03-25 08:56:12
dt1 structure
dt2 = datetime.datetime.strptime('2021-03-25 08:56:12', "%Y-%m-%d %H:%M:%S")
dt2 structure
The comparision fails as i try to compare a datetime object with a tuple which has a datetime object in it.
If I try to just assign the first element of the tuple (dt1) like so:
dt1 = fake.date_time()[0]
I get the follow error:
Error directly assign tuple element
But if i do the following, it works:
dt1 = fake.date_time()
dt1 = dt1[0]
What do I not understand here? :( And why isn't faker directly returning a datetime?
Thank you for any help.
I use python 3.7 and faker 6.6.2.
As I was preparing the whole code to be passed here, I discovered the issue.
I copied this line from a dict definition, and it had the comma at the end...
dt = fake.date_time(),
Obviously then python creates a tuple, I just didn't see this.
If you check the Faker date_time function source code you'll see only a single datetime.datetime object retuns:
def date_time(self, tzinfo=None, end_datetime=None):
"""
Get a datetime object for a date between January 1, 1970 and now
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('2005-08-16 20:39:21')
:return datetime
"""
# NOTE: On windows, the lowest value you can get from windows is 86400
# on the first day. Known python issue:
# https://bugs.python.org/issue30684
return datetime(1970, 1, 1, tzinfo=tzinfo) + \
timedelta(seconds=self.unix_time(end_datetime=end_datetime))
I suspect an unwanted change has been applied to the dt1 object (or it can be a debugger bug also), as I can see in the error clearly stated that the datetime.datetime object is not subscriptable . Would you add the complete code for further checking?
I am trying to use timestamp information to graph.
However, when I convert the number into hh:mm:ss. It does not work.
I have tried this:
timestamp = [dt.strptime(str(datetime.timedelta(seconds=round(t/1000))),'%H:%M:%S') for t in timestamp1]
Also I tried this
timestamp = [dt.strftime(dt.strptime(str(datetime.timedelta(seconds=round(t / 1000))), '%H:%M:%S'), '%H:%M:%S') for t in timestamp]
However, it is possible to see the list with the new values. However, I have problems with the graphs and these new values.
Can anybody help me?
Try using this and make sure to import the time module!
timestamp = [time.strftime('%H:%M:%S', time.gmtime(t/1000)) for t in timestamp1]
In your code you're using datetime.strptime(date_string, format) function, it's main use is to parse time strings in order to create datetime object.
In order to get a parsed string of a desired format you should use date.strftime(format) function instead.
So basically in your code you can only add it and should get the wanted result:
import datetime
from datetime import datetime as dt
timestamp = [dt.strftime(dt.strptime(str(datetime.timedelta(seconds=round(t / 1000))), '%H:%M:%S'), '%H:%M:%S') for t in timestamp1]
I'm not sure what was your input and desired output, but you could also use date.fromtimestamp(timestamp) for the parsing of timestamps
I am trying to filter by time to delete messages from an sqlite3 database. I am taking a string that is accurate to the minute, converting that to a datetime object, and using the filter function on the QuerySet of messages. However, the entry in the database is far more precise than the string, so the message I'm looking for is being filtered out as well.
I'm automatically generating the datetime object using
class Message(models.Model):
....
time = models.DateTimeField(auto_now_add=True)
I'm filtering using
Message.objects.all().filter(time=time)
For example, the string I'm using to create the datetime object to filter is 'Dec. 5, 2015, 5:07 PM' to create a datetime object '2015-12-05 05:07:00'. However, the message I'm looking for is from time '2015-12-05 17:07:19.308321'
Is there an option to make the auto-generated datetime objects less precise, to the minute instead of fraction of a second?