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]
Related
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.
I have a DataFrame with one columns that is a date and a time and is a string.
The format of the date and time is like this: 4/27/2021 12:39
This is what I have so far to try and convert the string into a datetime:
new_list = []
for i in range(len(open_times)):
date = df.iloc[i]['Open Datetime']
good_date = date.to_datetime()
# good_date = date.topydatetime()
new_list.append(good_date)
I have used to_pydatetime() in the past however the string was in a different format.
When I run the code from above I get this error: AttributeError: 'str' object has no attribute 'to_datetime' and I get the same error when I run the commented out line except with to_pydatetime.
Any thoughts on how to resolve this error? I think that this is happening because the format of the string is different than it typically is.
You need to use datetime.strptime(date_string, format) to convert a string to datetime type
from datetime import datetime
for i in range(len(open_times)):
date = df.iloc[i]['Open Datetime']
good_date = datetime.strptime(date, '%m/%d/%Y %H:%M')
But you could use pd.to_datetime directly
df['Open Datetime'] = pd.to_datetime(df['Open Datetime'])
# Convert a column to list
new_list = df['Open Datetime'].values.tolist()
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
My timedelta object looks like this: txdelta = 00:30:00. I want to add it to a datetime object but it consistently isn't working:
from datetime import datetime, date, time, timedelta
localdt = datetime.combine(datetime.strptime('2015-06-18', '%Y-%m-%d').date(),
(23:35:02+timedelta(txdelta)).time())
Note that the 23:35:02 is already a datetime object. I get this error message:
TypeError: unsupported type for timedelta days component: datetime.timedelta
What am I doing wrong?
The way you create your time object is strange. I strongly advice you to declare it this way if you're not used to it:
txdelta = timedelta(minutes=30)
tdelta = time(hour=1, minute=35, second=2)
If I got it well you tried to combine a date, a time and a timedelta. The full code below should do the trick:
from datetime import datetime, date, time, timedelta
txdelta = timedelta(minutes=30)
tdelta = time(hour=1, minute=35, second=2)
localdt = datetime.combine(datetime.strptime('2015-06-18', '%Y-%m-%d').date(), tdelta) + txdelta
print(localdt)
Basically, you combine a datetime object with a time one, and you simply add the timedelta object afterwards.
The output is:
2015-06-18 02:05:02
Users in my app have date_joined fields that are in this format: 2014-12-14 14:46:43.379518+00:00
In order to pass this datetime along to Intercom.io, it must be a UNIX timestamp like this: 1426020706 (this is not the same time, just an example).
I've tried several methods I've read here on Stack Overflow (nothing in this question has the same starting time format: Converting datetime.date to UTC timestamp in Python), but none have worked. mktime() seemed promising, but I got "'datetime.datetime' object has no attribute 'mktime'."
I just tried this:
import time
import dateutil.parser
import member.models import Member
member = Member.objects.get(email="aspeksnijder#outlook.com")
date_joined = member.date_joined
dt = dateutil.parser.parse(date_joined)
print int(time.mktime(dt.timetuple()))
It returned "'datetime.datetime' object has no attribute 'read'". How can I accomplish this?
It seems you have an aware datetime object. If you print it then it looks like:
2014-12-14 14:46:43.379518+00:00
To be sure print(repr(date_joined)).
Converting datetime.date to UTC timestamp in Python shows several ways how you could get the timestamp e.g.,
timestamp = date_joined.timestamp() # in Python 3.3+
Or on older Python versions:
from datetime import datetime
# local time = utc time + utc offset
utc_naive = date_joined.replace(tzinfo=None) - date_joined.utcoffset()
timestamp = (utc_naive - datetime(1970, 1, 1)).total_seconds()
Note: timestamp = calendar.timegm(date_joined.utctimetuple()) would also work in your case but it may return a wrong result silently if you pass it a naive datetime object that represents local time by mistake.
If your input is a time string then convert the time string into a datetime object first.
What about (using the dateutil and pytz packages):
import dateutil.parser
from datetime import datetime
import calendar
import pytz
def str2ts(s):
''' Turns a string into a non-naive datetime object, then get the timestamp '''
# However you get from your string to datetime.datetime object
dt = dateutil.parser.parse(s) # String to non-naive datetime
dt = pytz.utc.normalize(dt) # Normalize datetime to UTC
ts = calendar.timegm(dt.timetuple()) # Convert UTC datetime to UTC timestamp
return int(ts)
def ts2str(ts):
'''Convert a UTC timestamp into a UTC datetime, then format it to a string'''
dt = datetime.utcfromtimestamp(ts) # Convert a UTC timestamp to a naive datetime object
dt = dt.replace(tzinfo=pytz.utc) # Convert naive datetime to non-naive
return dt.strftime('%Y-%m-%d %H:%M:%S.%f%z')
Which we can test with:
# A list of strings corresponding to the same time, with different timezone offsets
ss = [
'2014-12-14 14:46:43.379518+00:00',
'2014-12-14 15:46:43.379518+01:00',
'2014-12-14 16:46:43.379518+02:00',
'2014-12-14 17:46:43.379518+03:00',
]
for s in ss:
ts = str2ts(s)
s2 = ts2str(ts)
print ts, s2
Output:
1418568403 2014-12-14 14:46:43.000000+0000
1418568403 2014-12-14 14:46:43.000000+0000
1418568403 2014-12-14 14:46:43.000000+0000
1418568403 2014-12-14 14:46:43.000000+0000
These output all the same timestamps, and "verification" formatted strings.
You can try the following Python 3 code:
import time, datetime
print(time.mktime(datetime.datetime.strptime("2014-12-14 14:46:43.379518", '%Y-%m-%d %H:%M:%S.%f').replace(tzinfo=datetime.timezone.utc).timetuple()))
which prints:
1418568403.0
I had that problem when I used input from Django's DateField, which is displayed in a form of XXXX-YY-ZZ: parse(django_datefield) causes the exception.
The solution: use str(django_datefield).
parse(str(django_datefield))
I know this is an old post, but I want to highlight that the answer is likely what #Peter said in his comment:
It looks like member.date_joined is already a datetime object, and there's no need to parse it. – Peter Feb 25 '17 at 0:33
So-- your model probably already parses into a datetime.datetime object for you.