Varchar to Datetime conversion

Posted on 2009-12-22
Last Modified: 2012-05-08
I have the following

2009/12/11 01:35:58.347000  in varchar/string variable.

I need the time part or both date &time as DATETIME,So that i can compare this with current datetime.

Could any one let me know how to convert this string to DATETIME.

I tried using COVERT() function,doesn't work.I got the following error message
"Conversion failed when converting datetime from character string'.


Question by:parpaa
    LVL 75

    Accepted Solution

    select CAST(LEFT('2009/12/11 01:35:58.347000',23) as datetime)

    Author Comment

    Thanks it's wotking fine

    Author Closing Comment

    Fast Response

    Expert Comment

    Here is sample SQL.  Problem is that the string contains extra information, you need to trim it

    DECLARE @s varchar(200), @d datetime
    SET @s = '2009/12/11 01:35:58.347000'
    SET @d = CONVERT(DATETIME, LEFT(@s, 23))
    --@d now contains the value in a datetime variable

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Suggested Solutions

    I've encountered valid database schemas that do not have a primary key.  For example, I use LogParser from Microsoft to push IIS logs into a SQL database table for processing and analysis.  However, occasionally due to user error or a scheduled task…
    In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
    This video discusses moving either the default database or any database to a new volume.
    Here's a very brief overview of the methods PRTG Network Monitor ( offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    10 Experts available now in Live!

    Get 1:1 Help Now