Skip to content
The Chat Archive
gpt-4-1106-preview· OpenAI WildChat-4.8M (AI2)

python datetime to timestamp

  1. User

    python datetime to timestamp

  2. Assistant

    In Python, you can convert a datetime object to a Unix timestamp (also known as POSIX time or epoch time) using the timestamp() method of datetime objects. Here's an example of how to do this:

    from datetime import datetime, timezone
    
    # Create a datetime object
    dt = datetime(2023, 4, 1, 12, 0)  # 1st April 2023, 12:00:00
    
    # If your datetime object is timezone-aware, you can directly use timestamp()
    timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
    
    # If your datetime object is naive, you should specify the timezone (UTC in this case)
    # It's recommended that UTC is used to avoid ambiguity with daylight saving times
    # Assuming the datetime object is in UTC, you can do this:
    naive_dt = datetime(2023, 4, 1, 12, 0)  # Naive datetime (no timezone info)
    aware_dt = naive_dt.replace(tzinfo=timezone.utc)  # Make it timezone-aware
    timestamp = aware_dt.timestamp()
    
    print(timestamp)
    

    The timestamp() method returns the time expressed as the number of seconds since the epoch (Unix epoch: 1970-01-01 00:00:00 UTC).

    If your datetime is in a different timezone, and you need to convert it to UTC before getting the timestamp, you could use the pytz library to deal with timezones:

    from datetime import datetime
    import pytz
    
    # Assuming the datetime object is in a specific timezone, for example, Eastern Time
    eastern = pytz.timezone('US/Eastern')
    aware_dt = eastern.localize(datetime(2023, 4, 1, 12, 0))
    
    # Convert to UTC before getting the timestamp
    utc_dt = aware_dt.astimezone(pytz.utc)
    timestamp = utc_dt.timestamp()
    
    print(timestamp)
    

    Remember that the timestamp is by convention expressed in UTC time, and it represents a universal point in time, irrespective of timezones.