Convert datetime object into a string - python

I need to convert a datetime into a string using numpy.
Is there another way to directly convert only one object to string that doesn't involve using the following function passing an array of 1 element (which returns an array too)?
numpy.datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')
With this function, I can make the conversion, but I just want to know if there is a more direct/clean way to do it.
Thanks in advance.

As we dont know what is inside of arr, I assume it is just datetime.now()
If so try this:
import datetime
datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
>>> '2022-07-28 10:27:34.986848'
If you need numpy version:
np.array(datetime.datetime.now(), dtype='datetime64[s]')
>>> array('2022-07-28T10:32:19', dtype='datetime64[s]')

if you just want to convert one numpy DateTime64 object into a string, here is the answer.
import datetime
yourdt = yourdt.astype(datetime.datetime)
yourdt_str = yourdt.strftime("%Y-%m-%d %H:%M:%S")
that's it

from datetime import datetime
now = datetime.now() # current date and time
year = now.strftime("%Y")
print("year:", year)
month = now.strftime("%m")
print("month:", month)
day = now.strftime("%d")
print("day:", day)
time = now.strftime("%H:%M:%S")
print("time:", time)
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)

Related

Subtracting datetime in string format with datetime format

I have 2 variables.
One is datetime in string format and the other is datetime in datetime.datetime format.
For example -
2021-09-06T07:58:19.032Z # string
2021-09-05 14:58:10.209675 # datetime.datetime
I want to find out the difference between these 2 times in seconds.
I think we need to have both in datetime before we can do this subtraction.
I'm having a hard time converting the string to datetime.
Can someone please help.
You can convert the string into datetime object with strptime()
An example with your given dates:
from datetime import datetime
# Assuming this is already a datetime object in your code, you don't need this part
# I needed this part to be able to use it as a datetime object
date1 = datetime.strptime("2021-09-05 14:58:10.209675", "%Y-%m-%d %H:%M:%S.%f")
## The part where the string is converted to datetime object
# Since the string has "T" and "Z", we will have to remove them before we convert
formatted = "2021-09-06T07:58:19.032Z".replace("T", " ").replace("Z", "")
>>> 2021-09-06 07:58:19.032
# Finally, converting the string
date2 = datetime.strptime(formatted, "%Y-%m-%d %H:%M:%S.%f")
# Now date2 variable is a datetime object
# Performing a simple operation
print(date1 - date2)
>>> -1 day, 6:59:51.177675
Convert the str to datetime via strptime() and then get the difference of the 2 datetime objects in seconds via total_seconds().
from datetime import datetime, timezone
# Input
dt1_str = "2021-09-06T07:58:19.032Z" # String type
dt2 = datetime(year=2021, month=9, day=5, hour=14, minute=58, second=10, microsecond=209675, tzinfo=timezone.utc) # datetime type
# Convert the string to datetime
dt1 = datetime.strptime(dt1_str, "%Y-%m-%dT%H:%M:%S.%f%z")
# Subtract the datetime objects and get the seconds
diff_seconds = (dt1 - dt2).total_seconds()
print(diff_seconds)
Output
61208.822325
The first string time you mention could be rfc3339 format.
A module called python-dateutil could help
import dateutil.parser
dateutil.parser.parse('2021-09-06T07:58:19.032Z')
datetime module could parse this time format by
datetime.datetime.strptime("2021-09-06T07:58:19.032Z","%Y-%m-%dT%H:%M:%S.%fZ")
But this way may cause trouble when get a time in another timezone because it doesn't support timezone offset.

Python: convert date format YYYY-mm-dd to dd-MON-yyyy with abbreviated month

I have a date that is a string in this format:
'2021-01-16'
And need to convert it to a string in this format:
'16-JAN-2021'
I am able to get most of it like this:
x = datetime.strptime('2021-01-16', '%Y-%m-%d')
x.strftime('%d-%b-%Y')
But the month is not fully capitalized:
'16-Jan-2021'
Just use upper() to capitalize the output string:
from datetime import datetime
x = datetime.strptime('2021-01-16', '%Y-%m-%d')
print(x.strftime('%d-%b-%Y').upper())
# 16-JAN-2021
You were almost there. Simply use upper().
>>> from datetime import datetime
>>> datetime.strptime('2021-01-16', '%Y-%m-%d').strftime('%d-%b-%Y').upper()
'16-JAN-2021'
x.strftime('%d-%b-%Y').upper()
I read answers with upper() function, here is another way using %^b
from datetime import datetime
date = datetime.strptime('2011-01-16', '%Y-%m-%d')
formatted_date = date.strftime('%d-%^b-%Y')
print(formatted_date)
Goodluck!

Extract only time (HH:MM) from datetime field - Odoo 10

I'a m trying to extract only time (Hour:Minute) from datetime field
Example:
today_with_hour = fields.Datetime(
string=u'hora',
default=fields.Datetime.now,
)
I would like to know how get only hour from today_with_hour in format
17:10:20
This is one way to extract:
from datetime import datetime
now = datetime.now()
print(str(now.hour)+':'+str(now.minute)+':'+str(now.second))
This may be better way to do it
You can use strftime
Example:
from datetime import datetime
datetime.now().strftime("%H:%M:%S")
In your case you can follow like this:
from datetime import datetime
datetime.strptime('20/06/2019 17:28:52', "%d/%m/%Y %H:%M:%S").time()
Output will be:
17:28:52
Better way to do is by using strftime().
dt = datetime.strptime('20/06/2019 17:28:52', "%d/%m/%Y %H:%M:%S")
dt.strftime("%H:%M:%S")
output:
17:28:52
To get the current time from the datetime.now()
datetime.datetime.now().time().strftime("%H:%M:%S")
O/P:
'11:16:17'
if you want to get the time with milliseconds also, use isoformat()
datetime.datetime.now().time().isoformat()
O/P:
'11:20:34.978272'

How to combine dates and times?

I want to add a time to a datetime. My initial datetime is: initial_datetime='2015-11-03 08:05:22' and is a string and this_hour and this_min are strings too. I use:
time='-7:00'
time = time.split(':')
this_hour = time[0]
this_min = time[1]
initial_datetime='2015-11-03 08:05:22'
new_date = datetime.combine(initial_datetime, time(this_hour, this_min))
+ timedelta(hours=4)
But there comes an error:
'str' object is not callable.
My desired output is the initial_datetime plus my time (in this case -7 hours ) and then add 4 hours. So, in my example, the new date should be '2015-11-03 05:05:22'.
datetime.combine is typically used to combine a date object with a time object rather than incrementing or decrementing a datetime object. In your case, you need to convert your datetime string to a datetime object and convert the parts of your time string to integers so you can add them to your datetime with timedelta. As an aside, be careful about using variable names, like time, that conflict with your imports.
from datetime import datetime, timedelta
dtstr = '2015-11-03 08:05:22'
tstr = '-7:00'
hours, minutes = [int(t) for t in tstr.split(':')]
dt = datetime.strptime(dtstr, '%Y-%m-%d %H:%M:%S') + timedelta(hours=hours+4, minutes=minutes)
print(dt)
# 2015-11-03 05:05:22

Is there a way to extract time from datetime objects in Python?

I want to extract time values from a datetime object in Python. This is the code I used:
t = '2018-12-16 17:59:00'
t.strftime('%H:%M:%S')
There is clearly something wrong with the code because I am getting this error:
AttributeError: 'str' object has no attribute 'strftime'
I am using Python 3 and I need to convert around 30000 datetime values.
from datetime import datetime as dt
t = '2018-12-16 17:59:00'
t = dt.strptime(t, '%Y-%m-%d %H:%M:%S')
print(t.strftime('%H:%M:%S'))
in datetime methods
strptime is the mehtod to convert from string to datetime
strftime is the method to convert from datetime to string
That's a string, not a datetime object. You should probably be using a datetime object:
t = datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
But if you want to use your string, you can splice it into two (space-separated) parts:
t = t.split() # t = ['2018-12-16', '17:59:00']
Then take the first part:
date = t[0]

Categories

Resources