How to convert millisecond Unix timestamp to readable date? - python

I have a string 1615070997520. This is a Unix timestamp, but this is for millisecond. When I convert this to date with converter, It gives me correct date (Saturday, March 6, 2021 10:49:57.520 PM GMT).
But with this code:
from datetime import datetime
ts = int("1615070997520")
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
It gives me an error which is ValueError: year 53149 is out of range.
Is there any way to convert it into correct date like yyyy-mm-dd hh:mm:ss.ms using Python?

Try this one
ts = int("1615070997520")/1000
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

Related

Convert string of dd-MON-yy to date in Python

I have a string in dd-MON-yy format. While converting to date in python, its is causing issue since the year is in tow digits.
datetime.datetime.strptime('17-JUN-03', '%d-%m-%y')
The error is,
ValueError: time data '17-JUN-03' does not match format '%d-%m-%y'
Try this:
import datetime
print(datetime.datetime.strptime('17-JUN-03', '%d-%b-%y'))
Result:
2003-06-17 00:00:00
Datetime format codes

Extract day of the week and hour from iso datetime stamp in Python

How can I extract the day of the week and the hour of the day from a timestamp in this format?
2020-08-17T01:54:38.000Z
So for the example above I would get Monday and 01 in return.
You could parse the string into a datetime object using strptime with a custom format, and then extract the info you need from it:
from datetime import datetime
dateStr = '2020-08-17T01:54:38.000Z'
dt = datetime.strptime(dateStr,'%Y-%m-%dT%H:%M:%S.%fZ')
hour = dt.strftime('%H')
dayOfWeek = dt.strftime('%A')

Unable to get time difference between to pandas dataframe columns

I have a pandas dataframe that contains a couple of columns. Two of which are start_time and end_time. In those columns the values look like - 2020-01-04 01:38:33 +0000 UTC
I am not able to create a datetime object from these strings because I am not able to get the format right -
df['start_time'] = pd.to_datetime(df['start_time'], format="yyyy-MM-dd HH:mm:ss +0000 UTC")
I also tried using yyyy-MM-dd HH:mm:ss %z UTC as a format
This gives the error -
ValueError: time data '2020-01-04 01:38:33 +0000 UTC' does not match format 'yyyy-MM-dd HH:mm:ss +0000 UTC' (match)
You just need to use the proper timestamp format that to_datetime will recognize
df['start_time'] = pd.to_datetime(df['start_time'], format="%Y-%m-%d %H:%M:%S +0000 UTC")
There are some notes below about this problem:
1. About your error
This gives the error -
You have parsed a wrong datetime format that will cause the error. For correct format check this one https://strftime.org/. Correct format for this problem would be: "%Y-%m-%d %H:%M:%S %z UTC"
2. Pandas limitation with timezone
Parsing UTC timezone as %z doesn't working on pd.Series (it only works on index value). So if you use this, it will not work:
df['startTime'] = pd.to_datetime(df.startTime, format="%Y-%m-%d %H:%M:%S %z UTC", utc=True)
Solution for this is using python built-in library for inferring the datetime data:
from datetime import datetime
f = lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S %z UTC")
df['startTime'] = pd.to_datetime(df.startTime.apply(f), utc=True)
#fmarm answer only help you dealing with date and hour data, not UTC timezone.

How can I convert text to DateTime?

I scraped a website and got the following Output:
2018-06-07T12:22:00+0200
2018-06-07T12:53:00+0200
2018-06-07T13:22:00+0200
Is there a way I can take the first one and convert it into a DateTime value?
Just parse the string into year, month, day, hour and minute integers and then create a new date time object with those variables.
Check out the datetime docs
You can convert string format of datetime to datetime object like this using strptime, here %z is the time zone :
import datetime
dt = "2018-06-07T12:22:00+0200"
ndt = datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S%z")
# output
2018-06-07 12:22:00+02:00
The following function (not mine) should help you with what you want:
df['date_column'] = pd.to_datetime(df['date_column'], format = '%d/%m/%Y %H:%M').dt.strftime('%Y%V')
You can mess around with the keys next to the % symbols to achieve what you want. You may, however, need to do some light cleaning of your values before you can use them with this function, i.e. replacing 2018-06-07T12:22:00+0200 with 2018-06-07 12:22.
You can use datetime lib.
from datetime import datetime
datetime_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
datetime.strptime documentation
Solution here

python parse string in date format to get the date

There is a string and a date format. I want to get the date based on format.
If date format is YYYY.MM.dd and string is 2017.01.01. It should transform to a valid date object.
How can I find the date.
You can use datetime module something like this :
from datetime import datetime
date_object = datetime.strptime('2017.01.01', '%Y.%m.%d') # Converting the given date string into a datetime object.
formatted_date = date_object.strftime('%c') #User Defined Output Format
print(formatted_date)
This will result in :
Sun Jan 1 00:00:00 2017
You can refer to the documentation here.

Categories