Convert string date to timestamp in Python
>>> import time
>>> import datetime
>>> s = "01/12/2011"
>>> time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
1322697600.0
Convert date to timestamp in Python
import time
timestamp = time.mktime(time.strptime('2015-10-20 22:24:46', '%Y-%m-%d %H:%M:%S'))
For more on the format string with all the % symbols, see python's time library.
Python: Converting string to timestamp with microseconds
There is no slot for the microseconds component in a time tuple:
>>> import time
>>> import datetime
>>> myDate = "2014-08-01 04:41:52,117"
>>> datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f").timetuple()
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=1, tm_hour=4, tm_min=41, tm_sec=52, tm_wday=4, tm_yday=213, tm_isdst=-1)
You'll have to add those manually:
>>> dt = datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f")
>>> time.mktime(dt.timetuple()) + (dt.microsecond / 1000000.0)
1406864512.117
The other method you could follow is to produce a timedelta()
object relative to the epoch, then get the timestamp with the timedelta.total_seconds()
method:
epoch = datetime.datetime.fromtimestamp(0)
(dt - epoch).total_seconds()
The use of a local time epoch is quite deliberate since you have a naive (not timezone-aware) datetime value. This method can be inaccurate based on the history of your local timezone however, see J.F. Sebastian's comment. You'd have to convert the naive datetime value to a timezone-aware datetime value first using your local timezone before subtracting a timezone-aware epoch.
As such, it is easier to stick to the timetuple()
+ microseconds approach.
Demo:
>>> dt = datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f")
>>> epoch = datetime.datetime.fromtimestamp(0)
>>> (dt - epoch).total_seconds()
1406864512.117
How to convert string date to datetime format for graphing in python
You can use datetime.datetime.strptime -
import datetime
string = '30.06.2019 07:00:00.000,1.13760,1.13760,1.13760,1.13760,0'.split(',')[0]
d = datetime.datetime.strptime(string, '%d.%m.%Y %H:%M:%S.%f')
or more to the point if you already have the comma-separated fields,
times.append(datetime.datetime.strptime(row[0], '%d.%m.%Y %H:%M:%S.%f')
I would recommend not using time
as the name of a variable since that will conflict with the time module which you may have imported. That kind of thing can really be hard to chase down.
Python - Parsing and converting string into timestamp
First part would be creating datetime object:
from datetime import datetime
date_string = "2017-02-14T09:51:46.000-0600"
# I'm using date_string[:-9] to skip ".000-0600"
format_date = datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%f%z'))
After which format date is:
print(format_date)
2017-02-14 09:51:46
And timestamp is:
print(format_date.timestamp())
1487062306.0
Little clarification here, on python reference page, you can see definition for '%Y-%m-%dT%H:%M:%S.%f%z')
format specifiers I used.
- %Y: Year with century as a decimal number, e.g. 1970, 1988, 2001, 2013
- %m: Month as a zero-padded decimal number (e.g. 01, 02, ..., 12)
- %d: Day of the month as a zero-padded decimal number (e.g. 01, 02, ..., 31)
- %H: Hour
(24-hour clock) as a zero-padded decimal number (e.g 00, 01, ..., 23) - %M: Minute as a zero-padded decimal number (e.g 00, 01, ..., 59)
- %S: Second as a zero-padded decimal number (e.g. 00, 01, ..., 59)
- %f: Microsecond as a decimal number, zero-padded on the left (000000, 000001, ..., 999999)
- %z: UTC offset in the form +HHMM or -HHMM, empty string if the the object is naive, (empty or +0000, -0400, +1030)
How to convert string timestamp to datetime object in Python
If convert values to datetimes in pandas, also there is added some default date
by to_datetime
:
df['col'] = pd.to_datetime(df['col'], format='%H:%M:%S.%f')
If need avoid it convert values to timedeltas by to_timedelta
:
df['col'] = pd.to_timedelta(df['col'])
How to convert string date column to timestamp in a new column in Python Pandas
Maybe try this?
import pandas as pd
import numpy as np
d = {'col1': ["2022-05-16T12:31:00Z", "2021-01-11T11:32:00Z"]}
df = pd.DataFrame(data=d)
df['col2'] = pd.to_datetime(df['col1'])
df['col2'] = df.col2.values.astype(np.int64) // 10 ** 9
df
Converting string date to nanoseconds timestamp
As pointed out in the comments, remove the +
in the format string.
timestamp_data= "2021-11-04 13:17:12.780000+00:00"
timestamp = datetime.datetime.strptime(timestamp_data, "%Y-%d-%m %H:%M:%S.%f%z")
will parse your string correctly.
Related Topics
How to Check If a Python Module Exists Without Importing It
Read Excel Cell Value and Not the Formula Computing It -Openpyxl
How to Count the Occurrence of a Certain Item in an Ndarray
Implementing Slicing in _Getitem_
How to Count Occurrence of Unique Values Inside a List
Is the Time-Complexity of Iterative String Append Actually O(N^2), or O(N)
Serializing Class Instance to JSON
Scipy.Misc Module Has No Attribute Imread
Scraping Dynamic Content Using Python-Scrapy
Using Pandas .Append Within for Loop
How to Find the Location of Python Module Sources